New upstream version 1.8.0+ds
authorJochen Sprickerhof <git@jochen.sprickerhof.de>
Sun, 23 Jan 2022 17:37:55 +0000 (18:37 +0100)
committerJochen Sprickerhof <git@jochen.sprickerhof.de>
Sun, 23 Jan 2022 17:37:55 +0000 (18:37 +0100)
103 files changed:
1  2 
mac/libusb/.gitignore
mac/libusb/COPYING
mac/libusb/README
mac/libusb/Xcode/config.h
mac/libusb/core.c
mac/libusb/descriptor.c
mac/libusb/hotplug.c
mac/libusb/hotplug.h
mac/libusb/io.c
mac/libusb/libusb.h
mac/libusb/libusb.pro
mac/libusb/libusbi.h
mac/libusb/os/darwin_usb.c
mac/libusb/os/darwin_usb.h
mac/libusb/os/threads_posix.c
mac/libusb/os/threads_posix.h
mac/libusb/strerror.c
mac/libusb/sync.c
mac/libusb/version.h
mac/libusb/version_nano.h
shapelib/.gitignore
shapelib/COPYING
shapelib/README.GPSBabel
shapelib/dbf_api.html
shapelib/dbfopen.c
shapelib/safileio.c
shapelib/shapefil.h
shapelib/shapelib.html
shapelib/shp_api.html
shapelib/shpopen.c
tools/qtci/LICENSE
tools/qtci/README.gpsbabel
tools/qtci/README.md
tools/qtci/extract-qt-installer
tools/qtci/find_qt_installer
tools/qtci/install-qt
tools/qtci/install-qt-online
tools/qtci/qt-install.qs
tools/uploadtool/LICENSE
tools/uploadtool/README.gpsbabel
tools/uploadtool/README.md
tools/uploadtool/upload.sh
tools/uploadtool/upload_appveyor.sh
zlib/.gitignore
zlib/ChangeLog
zlib/FAQ
zlib/Makefile.in.zlib
zlib/README
zlib/README.gpsbabel
zlib/adler32.c
zlib/algorithm.txt
zlib/compress.c
zlib/contrib/minizip/Makefile
zlib/contrib/minizip/Makefile.am
zlib/contrib/minizip/MiniZip64_Changes.txt
zlib/contrib/minizip/MiniZip64_info.txt
zlib/contrib/minizip/configure.ac
zlib/contrib/minizip/crypt.h
zlib/contrib/minizip/ioapi.c
zlib/contrib/minizip/ioapi.c.patch
zlib/contrib/minizip/ioapi.h
zlib/contrib/minizip/ioapi.h.patch
zlib/contrib/minizip/iowin32.c
zlib/contrib/minizip/iowin32.h
zlib/contrib/minizip/make_vms.com
zlib/contrib/minizip/miniunz.c
zlib/contrib/minizip/miniunzip.1
zlib/contrib/minizip/minizip.1
zlib/contrib/minizip/minizip.c
zlib/contrib/minizip/minizip.pc.in
zlib/contrib/minizip/mztools.c
zlib/contrib/minizip/mztools.h
zlib/contrib/minizip/unzip.c
zlib/contrib/minizip/unzip.h
zlib/contrib/minizip/zip.c
zlib/contrib/minizip/zip.h
zlib/crc32.c
zlib/crc32.h
zlib/deflate.c
zlib/deflate.h
zlib/gzclose.c
zlib/gzguts.h
zlib/gzlib.c
zlib/gzread.c
zlib/gzwrite.c
zlib/infback.c
zlib/inffast.c
zlib/inffast.h
zlib/inffixed.h
zlib/inflate.c
zlib/inflate.h
zlib/inftrees.c
zlib/inftrees.h
zlib/resync_zlib
zlib/trees.c
zlib/trees.h
zlib/uncompr.c
zlib/zconf.h
zlib/zconf.in.h
zlib/zlib.3
zlib/zlib.h
zlib/zutil.c
zlib/zutil.h

diff --cc mac/libusb/.gitignore
index 4d9b6b491f536787041f430e26123f379bba2938,4d9b6b491f536787041f430e26123f379bba2938..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,3 -1,3 +1,0 @@@
--/Makefile
--/libusb-1.0.a
--
diff --cc mac/libusb/COPYING
index 5ab7695ab8cabe0c5c8a814bb0ab1e8066578fbb,5ab7695ab8cabe0c5c8a814bb0ab1e8066578fbb..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,504 -1,504 +1,0 @@@
--                GNU LESSER GENERAL PUBLIC LICENSE
--                     Version 2.1, February 1999
--
-- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
-- 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-- Everyone is permitted to copy and distribute verbatim copies
-- of this license document, but changing it is not allowed.
--
--[This is the first released version of the Lesser GPL.  It also counts
-- as the successor of the GNU Library Public License, version 2, hence
-- the version number 2.1.]
--
--                          Preamble
--
--  The licenses for most software are designed to take away your
--freedom to share and change it.  By contrast, the GNU General Public
--Licenses are intended to guarantee your freedom to share and change
--free software--to make sure the software is free for all its users.
--
--  This license, the Lesser General Public License, applies to some
--specially designated software packages--typically libraries--of the
--Free Software Foundation and other authors who decide to use it.  You
--can use it too, but we suggest you first think carefully about whether
--this license or the ordinary General Public License is the better
--strategy to use in any particular case, based on the explanations below.
--
--  When we speak of free software, we are referring to freedom of use,
--not price.  Our General Public Licenses are designed to make sure that
--you have the freedom to distribute copies of free software (and charge
--for this service if you wish); that you receive source code or can get
--it if you want it; that you can change the software and use pieces of
--it in new free programs; and that you are informed that you can do
--these things.
--
--  To protect your rights, we need to make restrictions that forbid
--distributors to deny you these rights or to ask you to surrender these
--rights.  These restrictions translate to certain responsibilities for
--you if you distribute copies of the library or if you modify it.
--
--  For example, if you distribute copies of the library, whether gratis
--or for a fee, you must give the recipients all the rights that we gave
--you.  You must make sure that they, too, receive or can get the source
--code.  If you link other code with the library, you must provide
--complete object files to the recipients, so that they can relink them
--with the library after making changes to the library and recompiling
--it.  And you must show them these terms so they know their rights.
--
--  We protect your rights with a two-step method: (1) we copyright the
--library, and (2) we offer you this license, which gives you legal
--permission to copy, distribute and/or modify the library.
--
--  To protect each distributor, we want to make it very clear that
--there is no warranty for the free library.  Also, if the library is
--modified by someone else and passed on, the recipients should know
--that what they have is not the original version, so that the original
--author's reputation will not be affected by problems that might be
--introduced by others.
--\f
--  Finally, software patents pose a constant threat to the existence of
--any free program.  We wish to make sure that a company cannot
--effectively restrict the users of a free program by obtaining a
--restrictive license from a patent holder.  Therefore, we insist that
--any patent license obtained for a version of the library must be
--consistent with the full freedom of use specified in this license.
--
--  Most GNU software, including some libraries, is covered by the
--ordinary GNU General Public License.  This license, the GNU Lesser
--General Public License, applies to certain designated libraries, and
--is quite different from the ordinary General Public License.  We use
--this license for certain libraries in order to permit linking those
--libraries into non-free programs.
--
--  When a program is linked with a library, whether statically or using
--a shared library, the combination of the two is legally speaking a
--combined work, a derivative of the original library.  The ordinary
--General Public License therefore permits such linking only if the
--entire combination fits its criteria of freedom.  The Lesser General
--Public License permits more lax criteria for linking other code with
--the library.
--
--  We call this license the "Lesser" General Public License because it
--does Less to protect the user's freedom than the ordinary General
--Public License.  It also provides other free software developers Less
--of an advantage over competing non-free programs.  These disadvantages
--are the reason we use the ordinary General Public License for many
--libraries.  However, the Lesser license provides advantages in certain
--special circumstances.
--
--  For example, on rare occasions, there may be a special need to
--encourage the widest possible use of a certain library, so that it becomes
--a de-facto standard.  To achieve this, non-free programs must be
--allowed to use the library.  A more frequent case is that a free
--library does the same job as widely used non-free libraries.  In this
--case, there is little to gain by limiting the free library to free
--software only, so we use the Lesser General Public License.
--
--  In other cases, permission to use a particular library in non-free
--programs enables a greater number of people to use a large body of
--free software.  For example, permission to use the GNU C Library in
--non-free programs enables many more people to use the whole GNU
--operating system, as well as its variant, the GNU/Linux operating
--system.
--
--  Although the Lesser General Public License is Less protective of the
--users' freedom, it does ensure that the user of a program that is
--linked with the Library has the freedom and the wherewithal to run
--that program using a modified version of the Library.
--
--  The precise terms and conditions for copying, distribution and
--modification follow.  Pay close attention to the difference between a
--"work based on the library" and a "work that uses the library".  The
--former contains code derived from the library, whereas the latter must
--be combined with the library in order to run.
--\f
--                GNU LESSER GENERAL PUBLIC LICENSE
--   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
--
--  0. This License Agreement applies to any software library or other
--program which contains a notice placed by the copyright holder or
--other authorized party saying it may be distributed under the terms of
--this Lesser General Public License (also called "this License").
--Each licensee is addressed as "you".
--
--  A "library" means a collection of software functions and/or data
--prepared so as to be conveniently linked with application programs
--(which use some of those functions and data) to form executables.
--
--  The "Library", below, refers to any such software library or work
--which has been distributed under these terms.  A "work based on the
--Library" means either the Library or any derivative work under
--copyright law: that is to say, a work containing the Library or a
--portion of it, either verbatim or with modifications and/or translated
--straightforwardly into another language.  (Hereinafter, translation is
--included without limitation in the term "modification".)
--
--  "Source code" for a work means the preferred form of the work for
--making modifications to it.  For a library, complete source code means
--all the source code for all modules it contains, plus any associated
--interface definition files, plus the scripts used to control compilation
--and installation of the library.
--
--  Activities other than copying, distribution and modification are not
--covered by this License; they are outside its scope.  The act of
--running a program using the Library is not restricted, and output from
--such a program is covered only if its contents constitute a work based
--on the Library (independent of the use of the Library in a tool for
--writing it).  Whether that is true depends on what the Library does
--and what the program that uses the Library does.
--  
--  1. You may copy and distribute verbatim copies of the Library's
--complete source code as you receive it, in any medium, provided that
--you conspicuously and appropriately publish on each copy an
--appropriate copyright notice and disclaimer of warranty; keep intact
--all the notices that refer to this License and to the absence of any
--warranty; and distribute a copy of this License along with the
--Library.
--
--  You may charge a fee for the physical act of transferring a copy,
--and you may at your option offer warranty protection in exchange for a
--fee.
--\f
--  2. You may modify your copy or copies of the Library or any portion
--of it, thus forming a work based on the Library, and copy and
--distribute such modifications or work under the terms of Section 1
--above, provided that you also meet all of these conditions:
--
--    a) The modified work must itself be a software library.
--
--    b) You must cause the files modified to carry prominent notices
--    stating that you changed the files and the date of any change.
--
--    c) You must cause the whole of the work to be licensed at no
--    charge to all third parties under the terms of this License.
--
--    d) If a facility in the modified Library refers to a function or a
--    table of data to be supplied by an application program that uses
--    the facility, other than as an argument passed when the facility
--    is invoked, then you must make a good faith effort to ensure that,
--    in the event an application does not supply such function or
--    table, the facility still operates, and performs whatever part of
--    its purpose remains meaningful.
--
--    (For example, a function in a library to compute square roots has
--    a purpose that is entirely well-defined independent of the
--    application.  Therefore, Subsection 2d requires that any
--    application-supplied function or table used by this function must
--    be optional: if the application does not supply it, the square
--    root function must still compute square roots.)
--
--These requirements apply to the modified work as a whole.  If
--identifiable sections of that work are not derived from the Library,
--and can be reasonably considered independent and separate works in
--themselves, then this License, and its terms, do not apply to those
--sections when you distribute them as separate works.  But when you
--distribute the same sections as part of a whole which is a work based
--on the Library, the distribution of the whole must be on the terms of
--this License, whose permissions for other licensees extend to the
--entire whole, and thus to each and every part regardless of who wrote
--it.
--
--Thus, it is not the intent of this section to claim rights or contest
--your rights to work written entirely by you; rather, the intent is to
--exercise the right to control the distribution of derivative or
--collective works based on the Library.
--
--In addition, mere aggregation of another work not based on the Library
--with the Library (or with a work based on the Library) on a volume of
--a storage or distribution medium does not bring the other work under
--the scope of this License.
--
--  3. You may opt to apply the terms of the ordinary GNU General Public
--License instead of this License to a given copy of the Library.  To do
--this, you must alter all the notices that refer to this License, so
--that they refer to the ordinary GNU General Public License, version 2,
--instead of to this License.  (If a newer version than version 2 of the
--ordinary GNU General Public License has appeared, then you can specify
--that version instead if you wish.)  Do not make any other change in
--these notices.
--\f
--  Once this change is made in a given copy, it is irreversible for
--that copy, so the ordinary GNU General Public License applies to all
--subsequent copies and derivative works made from that copy.
--
--  This option is useful when you wish to copy part of the code of
--the Library into a program that is not a library.
--
--  4. You may copy and distribute the Library (or a portion or
--derivative of it, under Section 2) in object code or executable form
--under the terms of Sections 1 and 2 above provided that you accompany
--it with the complete corresponding machine-readable source code, which
--must be distributed under the terms of Sections 1 and 2 above on a
--medium customarily used for software interchange.
--
--  If distribution of object code is made by offering access to copy
--from a designated place, then offering equivalent access to copy the
--source code from the same place satisfies the requirement to
--distribute the source code, even though third parties are not
--compelled to copy the source along with the object code.
--
--  5. A program that contains no derivative of any portion of the
--Library, but is designed to work with the Library by being compiled or
--linked with it, is called a "work that uses the Library".  Such a
--work, in isolation, is not a derivative work of the Library, and
--therefore falls outside the scope of this License.
--
--  However, linking a "work that uses the Library" with the Library
--creates an executable that is a derivative of the Library (because it
--contains portions of the Library), rather than a "work that uses the
--library".  The executable is therefore covered by this License.
--Section 6 states terms for distribution of such executables.
--
--  When a "work that uses the Library" uses material from a header file
--that is part of the Library, the object code for the work may be a
--derivative work of the Library even though the source code is not.
--Whether this is true is especially significant if the work can be
--linked without the Library, or if the work is itself a library.  The
--threshold for this to be true is not precisely defined by law.
--
--  If such an object file uses only numerical parameters, data
--structure layouts and accessors, and small macros and small inline
--functions (ten lines or less in length), then the use of the object
--file is unrestricted, regardless of whether it is legally a derivative
--work.  (Executables containing this object code plus portions of the
--Library will still fall under Section 6.)
--
--  Otherwise, if the work is a derivative of the Library, you may
--distribute the object code for the work under the terms of Section 6.
--Any executables containing that work also fall under Section 6,
--whether or not they are linked directly with the Library itself.
--\f
--  6. As an exception to the Sections above, you may also combine or
--link a "work that uses the Library" with the Library to produce a
--work containing portions of the Library, and distribute that work
--under terms of your choice, provided that the terms permit
--modification of the work for the customer's own use and reverse
--engineering for debugging such modifications.
--
--  You must give prominent notice with each copy of the work that the
--Library is used in it and that the Library and its use are covered by
--this License.  You must supply a copy of this License.  If the work
--during execution displays copyright notices, you must include the
--copyright notice for the Library among them, as well as a reference
--directing the user to the copy of this License.  Also, you must do one
--of these things:
--
--    a) Accompany the work with the complete corresponding
--    machine-readable source code for the Library including whatever
--    changes were used in the work (which must be distributed under
--    Sections 1 and 2 above); and, if the work is an executable linked
--    with the Library, with the complete machine-readable "work that
--    uses the Library", as object code and/or source code, so that the
--    user can modify the Library and then relink to produce a modified
--    executable containing the modified Library.  (It is understood
--    that the user who changes the contents of definitions files in the
--    Library will not necessarily be able to recompile the application
--    to use the modified definitions.)
--
--    b) Use a suitable shared library mechanism for linking with the
--    Library.  A suitable mechanism is one that (1) uses at run time a
--    copy of the library already present on the user's computer system,
--    rather than copying library functions into the executable, and (2)
--    will operate properly with a modified version of the library, if
--    the user installs one, as long as the modified version is
--    interface-compatible with the version that the work was made with.
--
--    c) Accompany the work with a written offer, valid for at
--    least three years, to give the same user the materials
--    specified in Subsection 6a, above, for a charge no more
--    than the cost of performing this distribution.
--
--    d) If distribution of the work is made by offering access to copy
--    from a designated place, offer equivalent access to copy the above
--    specified materials from the same place.
--
--    e) Verify that the user has already received a copy of these
--    materials or that you have already sent this user a copy.
--
--  For an executable, the required form of the "work that uses the
--Library" must include any data and utility programs needed for
--reproducing the executable from it.  However, as a special exception,
--the materials to be distributed need not include anything that is
--normally distributed (in either source or binary form) with the major
--components (compiler, kernel, and so on) of the operating system on
--which the executable runs, unless that component itself accompanies
--the executable.
--
--  It may happen that this requirement contradicts the license
--restrictions of other proprietary libraries that do not normally
--accompany the operating system.  Such a contradiction means you cannot
--use both them and the Library together in an executable that you
--distribute.
--\f
--  7. You may place library facilities that are a work based on the
--Library side-by-side in a single library together with other library
--facilities not covered by this License, and distribute such a combined
--library, provided that the separate distribution of the work based on
--the Library and of the other library facilities is otherwise
--permitted, and provided that you do these two things:
--
--    a) Accompany the combined library with a copy of the same work
--    based on the Library, uncombined with any other library
--    facilities.  This must be distributed under the terms of the
--    Sections above.
--
--    b) Give prominent notice with the combined library of the fact
--    that part of it is a work based on the Library, and explaining
--    where to find the accompanying uncombined form of the same work.
--
--  8. You may not copy, modify, sublicense, link with, or distribute
--the Library except as expressly provided under this License.  Any
--attempt otherwise to copy, modify, sublicense, link with, or
--distribute the Library is void, and will automatically terminate your
--rights under this License.  However, parties who have received copies,
--or rights, from you under this License will not have their licenses
--terminated so long as such parties remain in full compliance.
--
--  9. You are not required to accept this License, since you have not
--signed it.  However, nothing else grants you permission to modify or
--distribute the Library or its derivative works.  These actions are
--prohibited by law if you do not accept this License.  Therefore, by
--modifying or distributing the Library (or any work based on the
--Library), you indicate your acceptance of this License to do so, and
--all its terms and conditions for copying, distributing or modifying
--the Library or works based on it.
--
--  10. Each time you redistribute the Library (or any work based on the
--Library), the recipient automatically receives a license from the
--original licensor to copy, distribute, link with or modify the Library
--subject to these terms and conditions.  You may not impose any further
--restrictions on the recipients' exercise of the rights granted herein.
--You are not responsible for enforcing compliance by third parties with
--this License.
--\f
--  11. If, as a consequence of a court judgment or allegation of patent
--infringement or for any other reason (not limited to patent issues),
--conditions are imposed on you (whether by court order, agreement or
--otherwise) that contradict the conditions of this License, they do not
--excuse you from the conditions of this License.  If you cannot
--distribute so as to satisfy simultaneously your obligations under this
--License and any other pertinent obligations, then as a consequence you
--may not distribute the Library at all.  For example, if a patent
--license would not permit royalty-free redistribution of the Library by
--all those who receive copies directly or indirectly through you, then
--the only way you could satisfy both it and this License would be to
--refrain entirely from distribution of the Library.
--
--If any portion of this section is held invalid or unenforceable under any
--particular circumstance, the balance of the section is intended to apply,
--and the section as a whole is intended to apply in other circumstances.
--
--It is not the purpose of this section to induce you to infringe any
--patents or other property right claims or to contest validity of any
--such claims; this section has the sole purpose of protecting the
--integrity of the free software distribution system which is
--implemented by public license practices.  Many people have made
--generous contributions to the wide range of software distributed
--through that system in reliance on consistent application of that
--system; it is up to the author/donor to decide if he or she is willing
--to distribute software through any other system and a licensee cannot
--impose that choice.
--
--This section is intended to make thoroughly clear what is believed to
--be a consequence of the rest of this License.
--
--  12. If the distribution and/or use of the Library is restricted in
--certain countries either by patents or by copyrighted interfaces, the
--original copyright holder who places the Library under this License may add
--an explicit geographical distribution limitation excluding those countries,
--so that distribution is permitted only in or among countries not thus
--excluded.  In such case, this License incorporates the limitation as if
--written in the body of this License.
--
--  13. The Free Software Foundation may publish revised and/or new
--versions of the Lesser General Public License from time to time.
--Such new versions will be similar in spirit to the present version,
--but may differ in detail to address new problems or concerns.
--
--Each version is given a distinguishing version number.  If the Library
--specifies a version number of this License which applies to it and
--"any later version", you have the option of following the terms and
--conditions either of that version or of any later version published by
--the Free Software Foundation.  If the Library does not specify a
--license version number, you may choose any version ever published by
--the Free Software Foundation.
--\f
--  14. If you wish to incorporate parts of the Library into other free
--programs whose distribution conditions are incompatible with these,
--write to the author to ask for permission.  For software which is
--copyrighted by the Free Software Foundation, write to the Free
--Software Foundation; we sometimes make exceptions for this.  Our
--decision will be guided by the two goals of preserving the free status
--of all derivatives of our free software and of promoting the sharing
--and reuse of software generally.
--
--                          NO WARRANTY
--
--  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
--WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
--EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
--OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
--KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
--IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
--LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
--THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
--
--  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
--WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
--AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
--FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
--CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
--LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
--RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
--FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
--SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
--DAMAGES.
--
--                   END OF TERMS AND CONDITIONS
--\f
--           How to Apply These Terms to Your New Libraries
--
--  If you develop a new library, and you want it to be of the greatest
--possible use to the public, we recommend making it free software that
--everyone can redistribute and change.  You can do so by permitting
--redistribution under these terms (or, alternatively, under the terms of the
--ordinary General Public License).
--
--  To apply these terms, attach the following notices to the library.  It is
--safest to attach them to the start of each source file to most effectively
--convey the exclusion of warranty; and each file should have at least the
--"copyright" line and a pointer to where the full notice is found.
--
--    <one line to give the library's name and a brief idea of what it does.>
--    Copyright (C) <year>  <name of author>
--
--    This library is free software; you can redistribute it and/or
--    modify it under the terms of the GNU Lesser General Public
--    License as published by the Free Software Foundation; either
--    version 2.1 of the License, or (at your option) any later version.
--
--    This library is distributed in the hope that it will be useful,
--    but WITHOUT ANY WARRANTY; without even the implied warranty of
--    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--    Lesser General Public License for more details.
--
--    You should have received a copy of the GNU Lesser General Public
--    License along with this library; if not, write to the Free Software
--    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
--
--Also add information on how to contact you by electronic and paper mail.
--
--You should also get your employer (if you work as a programmer) or your
--school, if any, to sign a "copyright disclaimer" for the library, if
--necessary.  Here is a sample; alter the names:
--
--  Yoyodyne, Inc., hereby disclaims all copyright interest in the
--  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
--
--  <signature of Ty Coon>, 1 April 1990
--  Ty Coon, President of Vice
--
--That's all there is to it!
--
--
diff --cc mac/libusb/README
index 498ebd813514b62dd1e679e83f958722e09242c2,77ef9b8a0822a942f853d1fe03245e1a48eb4fdf..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,13 -1,13 +1,0 @@@
- This is libusb-1.0.22 from https://libusb.info/.
 -This is libusb-1.0.24 from https://libusb.info/.
--Since we have such problems with people
--getting libusb successfully built - between the Universal Build issues
--and the fact that we have to work hard to go find where it's installed
--and unravel the shared library thing -it's easier to just include it 
--here.
--
--This code is covered under GPL.
--
--This is meant to be a stop-gap until we can get rid of libusb and use
--the IoKit framework natively.
--
--08-11-08 robertlipe
diff --cc mac/libusb/Xcode/config.h
index 14d152729de9ab2639bed5c90b677295a54d4336,59f3463352269488da3f41ff4064497dec29e6d1..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,25 -1,37 +1,0 @@@
--/* config.h.  Manually generated for Xcode.  */
--
- /* Default visibility */
- #define DEFAULT_VISIBILITY /**/
 -#include <AvailabilityMacros.h>
--
- /* Message logging */
 -/* Define to the attribute for default visibility. */
 -#define DEFAULT_VISIBILITY __attribute__ ((visibility ("default")))
 -
 -/* Define to 1 to enable message logging. */
--#define ENABLE_LOGGING 1
--
- /* Define to 1 if you have the <poll.h> header file. */
- #define HAVE_POLL_H 1
 -/* On 10.12 and later, use newly available clock_*() functions */
 -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
 -/* Define to 1 if you have the `clock_gettime' function. */
 -#define HAVE_CLOCK_GETTIME 1
 -#endif
 -
 -/* On 10.6 and later, use newly available pthread_threadid_np() function */
 -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
 -/* Define to 1 if you have the 'pthread_threadid_np' function. */
 -#define HAVE_PTHREAD_THREADID_NP 1
 -#endif
 -
 -/* Define to 1 if the system has the type `nfds_t'. */
 -#define HAVE_NFDS_T 1
--
--/* Define to 1 if you have the <sys/time.h> header file. */
--#define HAVE_SYS_TIME_H 1
- /* Darwin backend */
- #define OS_DARWIN 1
--
- /* type of second poll() argument */
- #define POLL_NFDS_TYPE nfds_t
 -/* Define to 1 if compiling for a POSIX platform. */
 -#define PLATFORM_POSIX 1
--
- /* Use POSIX Threads */
- #define THREADS_POSIX 1
 -/* Define to the attribute for enabling parameter checks on printf-like
 -   functions. */
 -#define PRINTF_FORMAT(a, b) __attribute__ ((__format__ (__printf__, a, b)))
--
- /* Use GNU extensions */
 -/* Enable GNU extensions. */
--#define _GNU_SOURCE 1
diff --cc mac/libusb/core.c
index 50f92f6b1b46a5840255e29eca234bab1aaeca3c,07d459c1269c64b39ce2e83b59bec9a3fd9626ab..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2579 -1,2737 +1,0 @@@
--/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
--/*
-- * Core functions for libusb
-- * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
-- * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
-- * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
- #include "config.h"
 -#include "libusbi.h"
 -#include "hotplug.h"
 -#include "version.h"
--
- #include <errno.h>
- #include <stdarg.h>
 -#ifdef __ANDROID__
 -#include <android/log.h>
 -#endif
--#include <stdio.h>
- #include <stdlib.h>
--#include <string.h>
- #ifdef HAVE_SYS_TYPES_H
- #include <sys/types.h>
- #endif
- #ifdef HAVE_SYS_TIME_H
- #include <sys/time.h>
- #endif
- #ifdef HAVE_SYSLOG_H
 -#ifdef HAVE_SYSLOG
--#include <syslog.h>
- #endif
- #ifdef __ANDROID__
- #include <android/log.h>
--#endif
- #include "libusbi.h"
- #include "hotplug.h"
--
- struct libusb_context *usbi_default_context = NULL;
 -struct libusb_context *usbi_default_context;
--static const struct libusb_version libusb_version_internal =
--      { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
--        LIBUSB_RC, "http://libusb.info" };
- static int default_context_refcnt = 0;
 -static int default_context_refcnt;
--static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
- static struct timespec timestamp_origin = { 0, 0 };
 -static struct timespec timestamp_origin;
 -#if defined(ENABLE_LOGGING) && !defined(USE_SYSTEM_LOGGING_FACILITY)
 -static libusb_log_cb log_handler;
 -#endif
--
--usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
--struct list_head active_contexts_list;
--
--/**
-- * \mainpage libusb-1.0 API Reference
-- *
-- * \section intro Introduction
-- *
-- * libusb is an open source library that allows you to communicate with USB
-  * devices from userspace. For more info, see the
 - * devices from user space. For more info, see the
-- * <a href="http://libusb.info">libusb homepage</a>.
-- *
-- * This documentation is aimed at application developers wishing to
-- * communicate with USB peripherals from their own software. After reviewing
-- * this documentation, feedback and questions can be sent to the
-- * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
-- *
-- * This documentation assumes knowledge of how to operate USB devices from
-- * a software standpoint (descriptors, configurations, interfaces, endpoints,
-- * control/bulk/interrupt/isochronous transfers, etc). Full information
-- * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
-- * Specification</a> which is available for free download. You can probably
-- * find less verbose introductions by searching the web.
-- *
-- * \section API Application Programming Interface (API)
-- *
-- * See the \ref libusb_api page for a complete list of the libusb functions.
-- *
-- * \section features Library features
-- *
-- * - All transfer types supported (control/bulk/interrupt/isochronous)
-- * - 2 transfer interfaces:
-- *    -# Synchronous (simple)
-- *    -# Asynchronous (more complicated, but more powerful)
-- * - Thread safe (although the asynchronous interface means that you
-- *   usually won't need to thread)
-- * - Lightweight with lean API
-- * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
-- * - Hotplug support (on some platforms). See \ref libusb_hotplug.
-- *
-- * \section gettingstarted Getting Started
-- *
-- * To begin reading the API documentation, start with the Modules page which
-- * links to the different categories of libusb's functionality.
-- *
-- * One decision you will have to make is whether to use the synchronous
-- * or the asynchronous data transfer interface. The \ref libusb_io documentation
-- * provides some insight into this topic.
-- *
-- * Some example programs can be found in the libusb source distribution under
-- * the "examples" subdirectory. The libusb homepage includes a list of
-- * real-life project examples which use libusb.
-- *
-- * \section errorhandling Error handling
-- *
-- * libusb functions typically return 0 on success or a negative error code
-- * on failure. These negative error codes relate to LIBUSB_ERROR constants
-- * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
-- *
-- * \section msglog Debug message logging
-- *
-- * libusb uses stderr for all logging. By default, logging is set to NONE,
-- * which means that no output will be produced. However, unless the library
-- * has been compiled with logging disabled, then any application calls to
-- * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level), or the setting of the
-- * environmental variable LIBUSB_DEBUG outside of the application, can result
-- * in logging being produced. Your application should therefore not close
-- * stderr, but instead direct it to the null device if its output is
-- * undesirable.
-- *
-- * The libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) function can be
-- * used to enable logging of certain messages. Under standard configuration,
-- * libusb doesn't really log much so you are advised to use this function
-- * to enable all error/warning/ informational messages. It will help debug
-- * problems with your software.
-- *
-- * The logged messages are unstructured. There is no one-to-one correspondence
-- * between messages being logged and success or failure return codes from
-- * libusb functions. There is no format to the messages, so you should not
-- * try to capture or parse them. They are not and will not be localized.
-- * These messages are not intended to being passed to your application user;
-- * instead, you should interpret the error codes returned from libusb functions
-- * and provide appropriate notification to the user. The messages are simply
-- * there to aid you as a programmer, and if you're confused because you're
-- * getting a strange error code from a libusb function, enabling message
-- * logging may give you a suitable explanation.
-- *
-- * The LIBUSB_DEBUG environment variable can be used to enable message logging
-- * at run-time. This environment variable should be set to a log level number,
-- * which is interpreted the same as the
-- * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) parameter. When this
-- * environment variable is set, the message logging verbosity level is fixed
-- * and libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) effectively does
-- * nothing.
-- *
-- * libusb can be compiled without any logging functions, useful for embedded
-- * systems. In this case, libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level)
-- * and the LIBUSB_DEBUG environment variable have no effects.
-- *
-- * libusb can also be compiled with verbose debugging messages always. When
-- * the library is compiled in this way, all messages of all verbosities are
-- * always logged. libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) and
-- * the LIBUSB_DEBUG environment variable have no effects.
-- *
-- * \section remarks Other remarks
-- *
-- * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
-- * to document these.
-- */
--
--/**
-- * \page libusb_caveats Caveats
 - *
 - * \section threadsafety Thread safety
 - *
 - * libusb is designed to be completely thread-safe, but as with any API it
 - * cannot prevent a user from sabotaging themselves, either intentionally or
 - * otherwise.
 - *
 - * Observe the following general guidelines:
 - *
 - * - Calls to functions that release a resource (e.g. libusb_close(),
 - *   libusb_free_config_descriptor()) should not be called concurrently on
 - *   the same resource. This is no different than concurrently calling free()
 - *   on the same allocated pointer.
 - * - Each individual \ref libusb_transfer should be prepared by a single
 - *   thread. In other words, no two threads should ever be concurrently
 - *   filling out the fields of a \ref libusb_transfer. You can liken this to
 - *   calling sprintf() with the same destination buffer from multiple threads.
 - *   The results will likely not be what you want unless the input parameters
 - *   are all the same, but its best to avoid this situation entirely.
 - * - Both the \ref libusb_transfer structure and its associated data buffer
 - *   should not be accessed between the time the transfer is submitted and the
 - *   time the completion callback is invoked. You can think of "ownership" of
 - *   these things as being transferred to libusb while the transfer is active.
 - * - The various "setter" functions (e.g. libusb_set_log_cb(),
 - *   libusb_set_pollfd_notifiers()) should not be called concurrently on the
 - *   resource. Though doing so will not lead to any undefined behavior, it
 - *   will likely produce results that the application does not expect.
 - *
 - * Rules for multiple threads and asynchronous I/O are detailed
 - * \ref libusb_mtasync "here".
-- *
-- * \section fork Fork considerations
-- *
-- * libusb is <em>not</em> designed to work across fork() calls. Depending on
-- * the platform, there may be resources in the parent process that are not
-- * available to the child (e.g. the hotplug monitor thread on Linux). In
-- * addition, since the parent and child will share libusb's internal file
-- * descriptors, using libusb in any way from the child could cause the parent
-- * process's \ref libusb_context to get into an inconsistent state.
-- *
-- * On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
-- * that it is safe to fork() and exec() without worrying about the child
-- * process needing to clean up state or having access to these file descriptors.
-- * Other platforms may not be so forgiving, so consider yourself warned!
-- *
-- * \section devresets Device resets
-- *
-- * The libusb_reset_device() function allows you to reset a device. If your
-- * program has to call such a function, it should obviously be aware that
-- * the reset will cause device state to change (e.g. register values may be
-- * reset).
-- *
-- * The problem is that any other program could reset the device your program
-- * is working with, at any time. libusb does not offer a mechanism to inform
-- * you when this has happened, so if someone else resets your device it will
-- * not be clear to your own program why the device state has changed.
-- *
-  * Ultimately, this is a limitation of writing drivers in userspace.
 - * Ultimately, this is a limitation of writing drivers in user space.
-- * Separation from the USB stack in the underlying kernel makes it difficult
-- * for the operating system to deliver such notifications to your program.
-- * The Linux kernel USB stack allows such reset notifications to be delivered
-- * to in-kernel USB drivers, but it is not clear how such notifications could
-  * be delivered to second-class drivers that live in userspace.
 - * be delivered to second-class drivers that live in user space.
-- *
-- * \section blockonly Blocking-only functionality
-- *
-- * The functionality listed below is only available through synchronous,
-- * blocking functions. There are no asynchronous/non-blocking alternatives,
-- * and no clear ways of implementing these.
-- *
-- * - Configuration activation (libusb_set_configuration())
-- * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
-- * - Releasing of interfaces (libusb_release_interface())
-- * - Clearing of halt/stall condition (libusb_clear_halt())
-- * - Device resets (libusb_reset_device())
-- *
-- * \section configsel Configuration selection and handling
-- *
-- * When libusb presents a device handle to an application, there is a chance
-- * that the corresponding device may be in unconfigured state. For devices
-- * with multiple configurations, there is also a chance that the configuration
-- * currently selected is not the one that the application wants to use.
-- *
-- * The obvious solution is to add a call to libusb_set_configuration() early
-- * on during your device initialization routines, but there are caveats to
-- * be aware of:
-- * -# If the device is already in the desired configuration, calling
-- *    libusb_set_configuration() using the same configuration value will cause
-- *    a lightweight device reset. This may not be desirable behaviour.
-- * -# In the case where the desired configuration is already active, libusb
-- *    may not even be able to perform a lightweight device reset. For example,
-- *    take my USB keyboard with fingerprint reader: I'm interested in driving
-- *    the fingerprint reader interface through libusb, but the kernel's
-- *    USB-HID driver will almost always have claimed the keyboard interface.
-- *    Because the kernel has claimed an interface, it is not even possible to
-- *    perform the lightweight device reset, so libusb_set_configuration() will
-- *    fail. (Luckily the device in question only has a single configuration.)
-- * -# libusb will be unable to set a configuration if other programs or
-- *    drivers have claimed interfaces. In particular, this means that kernel
-- *    drivers must be detached from all the interfaces before
-- *    libusb_set_configuration() may succeed.
-- *
-- * One solution to some of the above problems is to consider the currently
-- * active configuration. If the configuration we want is already active, then
-- * we don't have to select any configuration:
--\code
--cfg = -1;
--libusb_get_configuration(dev, &cfg);
--if (cfg != desired)
--      libusb_set_configuration(dev, desired);
--\endcode
-- *
-- * This is probably suitable for most scenarios, but is inherently racy:
-- * another application or driver may change the selected configuration
-- * <em>after</em> the libusb_get_configuration() call.
-- *
-- * Even in cases where libusb_set_configuration() succeeds, consider that other
-- * applications or drivers may change configuration after your application
-- * calls libusb_set_configuration().
-- *
-- * One possible way to lock your device into a specific configuration is as
-- * follows:
-- * -# Set the desired configuration (or use the logic above to realise that
-- *    it is already in the desired configuration)
-- * -# Claim the interface that you wish to use
-- * -# Check that the currently active configuration is the one that you want
-- *    to use.
-- *
-- * The above method works because once an interface is claimed, no application
-- * or driver is able to select another configuration.
-- *
-- * \section earlycomp Early transfer completion
-- *
-- * NOTE: This section is currently Linux-centric. I am not sure if any of these
-- * considerations apply to Darwin or other platforms.
-- *
-- * When a transfer completes early (i.e. when less data is received/sent in
-- * any one packet than the transfer buffer allows for) then libusb is designed
-- * to terminate the transfer immediately, not transferring or receiving any
-- * more data unless other transfers have been queued by the user.
-- *
-- * On legacy platforms, libusb is unable to do this in all situations. After
-- * the incomplete packet occurs, "surplus" data may be transferred. For recent
-- * versions of libusb, this information is kept (the data length of the
-- * transfer is updated) and, for device-to-host transfers, any surplus data was
-- * added to the buffer. Still, this is not a nice solution because it loses the
-- * information about the end of the short packet, and the user probably wanted
-- * that surplus data to arrive in the next logical transfer.
-- *
-- * \section zlp Zero length packets
-- *
-- * - libusb is able to send a packet of zero length to an endpoint simply by
-- * submitting a transfer of zero length.
-- * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
-- * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
-- */
--
--/**
-- * \page libusb_contexts Contexts
-- *
-- * It is possible that libusb may be used simultaneously from two independent
-- * libraries linked into the same executable. For example, if your application
-- * has a plugin-like system which allows the user to dynamically load a range
-- * of modules into your program, it is feasible that two independently
-- * developed modules may both use libusb.
-- *
-- * libusb is written to allow for these multiple user scenarios. The two
-- * "instances" of libusb will not interfere: libusb_set_option() calls
-- * from one user will not affect the same settings for other users, other
-- * users can continue using libusb after one of them calls libusb_exit(), etc.
-- *
-- * This is made possible through libusb's <em>context</em> concept. When you
-- * call libusb_init(), you are (optionally) given a context. You can then pass
-- * this context pointer back into future libusb functions.
-- *
-- * In order to keep things simple for more simplistic applications, it is
-- * legal to pass NULL to all functions requiring a context pointer (as long as
-- * you're sure no other code will attempt to use libusb from the same process).
-- * When you pass NULL, the default context will be used. The default context
-- * is created the first time a process calls libusb_init() when no other
-- * context is alive. Contexts are destroyed during libusb_exit().
-- *
-- * The default context is reference-counted and can be shared. That means that
-- * if libusb_init(NULL) is called twice within the same process, the two
-- * users end up sharing the same context. The deinitialization and freeing of
-- * the default context will only happen when the last user calls libusb_exit().
-- * In other words, the default context is created and initialized when its
-- * reference count goes from 0 to 1, and is deinitialized and destroyed when
-- * its reference count goes from 1 to 0.
-- *
-- * You may be wondering why only a subset of libusb functions require a
-- * context pointer in their function definition. Internally, libusb stores
-- * context pointers in other objects (e.g. libusb_device instances) and hence
-- * can infer the context from those objects.
-- */
--
-- /**
--  * \page libusb_api Application Programming Interface
--  *
--  * This is the complete list of libusb functions, structures and
--  * enumerations in alphabetical order.
--  *
--  * \section Functions
--  * - libusb_alloc_streams()
--  * - libusb_alloc_transfer()
--  * - libusb_attach_kernel_driver()
--  * - libusb_bulk_transfer()
--  * - libusb_cancel_transfer()
--  * - libusb_claim_interface()
--  * - libusb_clear_halt()
--  * - libusb_close()
--  * - libusb_control_transfer()
--  * - libusb_control_transfer_get_data()
--  * - libusb_control_transfer_get_setup()
--  * - libusb_cpu_to_le16()
--  * - libusb_detach_kernel_driver()
--  * - libusb_dev_mem_alloc()
--  * - libusb_dev_mem_free()
--  * - libusb_error_name()
--  * - libusb_event_handler_active()
--  * - libusb_event_handling_ok()
--  * - libusb_exit()
--  * - libusb_fill_bulk_stream_transfer()
--  * - libusb_fill_bulk_transfer()
--  * - libusb_fill_control_setup()
--  * - libusb_fill_control_transfer()
--  * - libusb_fill_interrupt_transfer()
--  * - libusb_fill_iso_transfer()
--  * - libusb_free_bos_descriptor()
--  * - libusb_free_config_descriptor()
--  * - libusb_free_container_id_descriptor()
--  * - libusb_free_device_list()
--  * - libusb_free_pollfds()
--  * - libusb_free_ss_endpoint_companion_descriptor()
--  * - libusb_free_ss_usb_device_capability_descriptor()
--  * - libusb_free_streams()
--  * - libusb_free_transfer()
--  * - libusb_free_usb_2_0_extension_descriptor()
--  * - libusb_get_active_config_descriptor()
--  * - libusb_get_bos_descriptor()
--  * - libusb_get_bus_number()
--  * - libusb_get_config_descriptor()
--  * - libusb_get_config_descriptor_by_value()
--  * - libusb_get_configuration()
--  * - libusb_get_container_id_descriptor()
--  * - libusb_get_descriptor()
--  * - libusb_get_device()
--  * - libusb_get_device_address()
--  * - libusb_get_device_descriptor()
--  * - libusb_get_device_list()
--  * - libusb_get_device_speed()
--  * - libusb_get_iso_packet_buffer()
--  * - libusb_get_iso_packet_buffer_simple()
--  * - libusb_get_max_iso_packet_size()
--  * - libusb_get_max_packet_size()
--  * - libusb_get_next_timeout()
--  * - libusb_get_parent()
--  * - libusb_get_pollfds()
--  * - libusb_get_port_number()
--  * - libusb_get_port_numbers()
--  * - libusb_get_port_path()
--  * - libusb_get_ss_endpoint_companion_descriptor()
--  * - libusb_get_ss_usb_device_capability_descriptor()
--  * - libusb_get_string_descriptor()
--  * - libusb_get_string_descriptor_ascii()
--  * - libusb_get_usb_2_0_extension_descriptor()
--  * - libusb_get_version()
--  * - libusb_handle_events()
--  * - libusb_handle_events_completed()
--  * - libusb_handle_events_locked()
--  * - libusb_handle_events_timeout()
--  * - libusb_handle_events_timeout_completed()
--  * - libusb_has_capability()
--  * - libusb_hotplug_deregister_callback()
--  * - libusb_hotplug_register_callback()
--  * - libusb_init()
--  * - libusb_interrupt_event_handler()
--  * - libusb_interrupt_transfer()
--  * - libusb_kernel_driver_active()
--  * - libusb_lock_events()
--  * - libusb_lock_event_waiters()
--  * - libusb_open()
--  * - libusb_open_device_with_vid_pid()
--  * - libusb_pollfds_handle_timeouts()
--  * - libusb_ref_device()
--  * - libusb_release_interface()
--  * - libusb_reset_device()
--  * - libusb_set_auto_detach_kernel_driver()
--  * - libusb_set_configuration()
--  * - libusb_set_debug()
 -  * - libusb_set_log_cb()
--  * - libusb_set_interface_alt_setting()
--  * - libusb_set_iso_packet_lengths()
--  * - libusb_set_option()
--  * - libusb_setlocale()
--  * - libusb_set_pollfd_notifiers()
--  * - libusb_strerror()
--  * - libusb_submit_transfer()
--  * - libusb_transfer_get_stream_id()
--  * - libusb_transfer_set_stream_id()
--  * - libusb_try_lock_events()
--  * - libusb_unlock_events()
--  * - libusb_unlock_event_waiters()
--  * - libusb_unref_device()
--  * - libusb_wait_for_event()
 -  * - libusb_wrap_sys_device()
--  *
--  * \section Structures
--  * - libusb_bos_descriptor
--  * - libusb_bos_dev_capability_descriptor
--  * - libusb_config_descriptor
--  * - libusb_container_id_descriptor
--  * - \ref libusb_context
--  * - libusb_control_setup
--  * - \ref libusb_device
--  * - libusb_device_descriptor
--  * - \ref libusb_device_handle
--  * - libusb_endpoint_descriptor
--  * - libusb_interface
--  * - libusb_interface_descriptor
--  * - libusb_iso_packet_descriptor
--  * - libusb_pollfd
--  * - libusb_ss_endpoint_companion_descriptor
--  * - libusb_ss_usb_device_capability_descriptor
--  * - libusb_transfer
--  * - libusb_usb_2_0_extension_descriptor
--  * - libusb_version
--  *
--  * \section Enums
--  * - \ref libusb_bos_type
--  * - \ref libusb_capability
--  * - \ref libusb_class_code
--  * - \ref libusb_descriptor_type
--  * - \ref libusb_endpoint_direction
 -  * - \ref libusb_endpoint_transfer_type
--  * - \ref libusb_error
--  * - \ref libusb_iso_sync_type
--  * - \ref libusb_iso_usage_type
--  * - \ref libusb_log_level
--  * - \ref libusb_option
--  * - \ref libusb_request_recipient
--  * - \ref libusb_request_type
--  * - \ref libusb_speed
--  * - \ref libusb_ss_usb_device_capability_attributes
--  * - \ref libusb_standard_request
--  * - \ref libusb_supported_speed
--  * - \ref libusb_transfer_flags
--  * - \ref libusb_transfer_status
--  * - \ref libusb_transfer_type
--  * - \ref libusb_usb_2_0_extension_attributes
--  */
--
--/**
-- * @defgroup libusb_lib Library initialization/deinitialization
-- * This page details how to initialize and deinitialize libusb. Initialization
-- * must be performed before using any libusb functionality, and similarly you
-- * must not call any libusb functions after deinitialization.
-- */
--
--/**
-- * @defgroup libusb_dev Device handling and enumeration
-- * The functionality documented below is designed to help with the following
-- * operations:
-- * - Enumerating the USB devices currently attached to the system
-- * - Choosing a device to operate from your software
-- * - Opening and closing the chosen device
-- *
-- * \section nutshell In a nutshell...
-- *
-- * The description below really makes things sound more complicated than they
-- * actually are. The following sequence of function calls will be suitable
-- * for almost all scenarios and does not require you to have such a deep
-- * understanding of the resource management issues:
-- * \code
--// discover devices
--libusb_device **list;
--libusb_device *found = NULL;
--ssize_t cnt = libusb_get_device_list(NULL, &list);
--ssize_t i = 0;
--int err = 0;
--if (cnt < 0)
--      error();
--
--for (i = 0; i < cnt; i++) {
--      libusb_device *device = list[i];
--      if (is_interesting(device)) {
--              found = device;
--              break;
--      }
--}
--
--if (found) {
--      libusb_device_handle *handle;
--
--      err = libusb_open(found, &handle);
--      if (err)
--              error();
--      // etc
--}
--
--libusb_free_device_list(list, 1);
--\endcode
-- *
-- * The two important points:
-- * - You asked libusb_free_device_list() to unreference the devices (2nd
-- *   parameter)
-- * - You opened the device before freeing the list and unreferencing the
-- *   devices
-- *
-- * If you ended up with a handle, you can now proceed to perform I/O on the
-- * device.
-- *
-- * \section devshandles Devices and device handles
-- * libusb has a concept of a USB device, represented by the
-- * \ref libusb_device opaque type. A device represents a USB device that
-- * is currently or was previously connected to the system. Using a reference
-- * to a device, you can determine certain information about the device (e.g.
-- * you can read the descriptor data).
-- *
-- * The libusb_get_device_list() function can be used to obtain a list of
-- * devices currently connected to the system. This is known as device
-- * discovery.
-- *
-- * Just because you have a reference to a device does not mean it is
-- * necessarily usable. The device may have been unplugged, you may not have
-- * permission to operate such device, or another program or driver may be
-- * using the device.
-- *
-- * When you've found a device that you'd like to operate, you must ask
-- * libusb to open the device using the libusb_open() function. Assuming
-- * success, libusb then returns you a <em>device handle</em>
-- * (a \ref libusb_device_handle pointer). All "real" I/O operations then
-- * operate on the handle rather than the original device pointer.
-- *
-- * \section devref Device discovery and reference counting
-- *
-- * Device discovery (i.e. calling libusb_get_device_list()) returns a
-- * freshly-allocated list of devices. The list itself must be freed when
-- * you are done with it. libusb also needs to know when it is OK to free
-- * the contents of the list - the devices themselves.
-- *
-- * To handle these issues, libusb provides you with two separate items:
-- * - A function to free the list itself
-- * - A reference counting system for the devices inside
-- *
-- * New devices presented by the libusb_get_device_list() function all have a
-- * reference count of 1. You can increase and decrease reference count using
-- * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
-- * its reference count reaches 0.
-- *
-- * With the above information in mind, the process of opening a device can
-- * be viewed as follows:
-- * -# Discover devices using libusb_get_device_list().
-- * -# Choose the device that you want to operate, and call libusb_open().
-- * -# Unref all devices in the discovered device list.
-- * -# Free the discovered device list.
-- *
-- * The order is important - you must not unreference the device before
-- * attempting to open it, because unreferencing it may destroy the device.
-- *
-- * For convenience, the libusb_free_device_list() function includes a
-- * parameter to optionally unreference all the devices in the list before
-- * freeing the list itself. This combines steps 3 and 4 above.
-- *
-- * As an implementation detail, libusb_open() actually adds a reference to
-- * the device in question. This is because the device remains available
-- * through the handle via libusb_get_device(). The reference is deleted during
-- * libusb_close().
-- */
--
--/** @defgroup libusb_misc Miscellaneous */
--
--/* we traverse usbfs without knowing how many devices we are going to find.
-- * so we create this discovered_devs model which is similar to a linked-list
-- * which grows when required. it can be freed once discovery has completed,
-- * eliminating the need for a list node in the libusb_device structure
-- * itself. */
--#define DISCOVERED_DEVICES_SIZE_STEP 8
--
--static struct discovered_devs *discovered_devs_alloc(void)
--{
--      struct discovered_devs *ret =
--              malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
--
--      if (ret) {
--              ret->len = 0;
--              ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
--      }
--      return ret;
--}
--
--static void discovered_devs_free(struct discovered_devs *discdevs)
--{
--      size_t i;
--
--      for (i = 0; i < discdevs->len; i++)
--              libusb_unref_device(discdevs->devices[i]);
--
--      free(discdevs);
--}
--
--/* append a device to the discovered devices collection. may realloc itself,
-- * returning new discdevs. returns NULL on realloc failure. */
--struct discovered_devs *discovered_devs_append(
--      struct discovered_devs *discdevs, struct libusb_device *dev)
--{
--      size_t len = discdevs->len;
--      size_t capacity;
--      struct discovered_devs *new_discdevs;
--
--      /* if there is space, just append the device */
--      if (len < discdevs->capacity) {
--              discdevs->devices[len] = libusb_ref_device(dev);
--              discdevs->len++;
--              return discdevs;
--      }
--
--      /* exceeded capacity, need to grow */
--      usbi_dbg("need to increase capacity");
--      capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
--      /* can't use usbi_reallocf here because in failure cases it would
--       * free the existing discdevs without unreferencing its devices. */
--      new_discdevs = realloc(discdevs,
--              sizeof(*discdevs) + (sizeof(void *) * capacity));
--      if (!new_discdevs) {
--              discovered_devs_free(discdevs);
--              return NULL;
--      }
--
--      discdevs = new_discdevs;
--      discdevs->capacity = capacity;
--      discdevs->devices[len] = libusb_ref_device(dev);
--      discdevs->len++;
--
--      return discdevs;
--}
--
--/* Allocate a new device with a specific session ID. The returned device has
-- * a reference count of 1. */
--struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
--      unsigned long session_id)
--{
--      size_t priv_size = usbi_backend.device_priv_size;
-       struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
-       int r;
 -      struct libusb_device *dev = calloc(1, PTR_ALIGN(sizeof(*dev)) + priv_size);
--
--      if (!dev)
--              return NULL;
--
-       r = usbi_mutex_init(&dev->lock);
-       if (r) {
-               free(dev);
-               return NULL;
-       }
 -      usbi_mutex_init(&dev->lock);
--
--      dev->ctx = ctx;
--      dev->refcnt = 1;
--      dev->session_data = session_id;
--      dev->speed = LIBUSB_SPEED_UNKNOWN;
--
--      if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
--              usbi_connect_device (dev);
--      }
--
--      return dev;
--}
--
--void usbi_connect_device(struct libusb_device *dev)
--{
--      struct libusb_context *ctx = DEVICE_CTX(dev);
--
--      dev->attached = 1;
--
--      usbi_mutex_lock(&dev->ctx->usb_devs_lock);
--      list_add(&dev->list, &dev->ctx->usb_devs);
--      usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
--
--      /* Signal that an event has occurred for this device if we support hotplug AND
--       * the hotplug message list is ready. This prevents an event from getting raised
--       * during initial enumeration. */
--      if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
--              usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
--      }
--}
--
--void usbi_disconnect_device(struct libusb_device *dev)
--{
--      struct libusb_context *ctx = DEVICE_CTX(dev);
--
--      usbi_mutex_lock(&dev->lock);
--      dev->attached = 0;
--      usbi_mutex_unlock(&dev->lock);
--
--      usbi_mutex_lock(&ctx->usb_devs_lock);
--      list_del(&dev->list);
--      usbi_mutex_unlock(&ctx->usb_devs_lock);
--
--      /* Signal that an event has occurred for this device if we support hotplug AND
--       * the hotplug message list is ready. This prevents an event from getting raised
--       * during initial enumeration. libusb_handle_events will take care of dereferencing
--       * the device. */
--      if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
--              usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
--      }
--}
--
--/* Perform some final sanity checks on a newly discovered device. If this
-- * function fails (negative return code), the device should not be added
-- * to the discovered device list. */
--int usbi_sanitize_device(struct libusb_device *dev)
--{
-       int r;
--      uint8_t num_configurations;
--
-       r = usbi_device_cache_descriptor(dev);
-       if (r < 0)
-               return r;
 -      if (dev->device_descriptor.bLength != LIBUSB_DT_DEVICE_SIZE ||
 -          dev->device_descriptor.bDescriptorType != LIBUSB_DT_DEVICE) {
 -              usbi_err(DEVICE_CTX(dev), "invalid device descriptor");
 -              return LIBUSB_ERROR_IO;
 -      }
--
--      num_configurations = dev->device_descriptor.bNumConfigurations;
--      if (num_configurations > USB_MAXCONFIG) {
--              usbi_err(DEVICE_CTX(dev), "too many configurations");
--              return LIBUSB_ERROR_IO;
-       } else if (0 == num_configurations)
 -      } else if (0 == num_configurations) {
--              usbi_dbg("zero configurations, maybe an unauthorized device");
 -      }
--
-       dev->num_configurations = num_configurations;
--      return 0;
--}
--
--/* Examine libusb's internal list of known devices, looking for one with
-- * a specific session ID. Returns the matching device if it was found, and
-- * NULL otherwise. */
--struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
--      unsigned long session_id)
--{
--      struct libusb_device *dev;
--      struct libusb_device *ret = NULL;
--
--      usbi_mutex_lock(&ctx->usb_devs_lock);
-       list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
 -      for_each_device(ctx, dev) {
--              if (dev->session_data == session_id) {
--                      ret = libusb_ref_device(dev);
--                      break;
--              }
 -      }
--      usbi_mutex_unlock(&ctx->usb_devs_lock);
--
--      return ret;
--}
--
--/** @ingroup libusb_dev
-- * Returns a list of USB devices currently attached to the system. This is
-- * your entry point into finding a USB device to operate.
-- *
-- * You are expected to unreference all the devices when you are done with
-- * them, and then free the list with libusb_free_device_list(). Note that
-- * libusb_free_device_list() can unref all the devices for you. Be careful
-- * not to unreference a device you are about to open until after you have
-- * opened it.
-- *
-- * This return value of this function indicates the number of devices in
-- * the resultant list. The list is actually one element larger, as it is
-- * NULL-terminated.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param list output location for a list of devices. Must be later freed with
-- * libusb_free_device_list().
-- * \returns the number of devices in the outputted list, or any
-- * \ref libusb_error according to errors encountered by the backend.
-- */
--ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
--      libusb_device ***list)
--{
--      struct discovered_devs *discdevs = discovered_devs_alloc();
--      struct libusb_device **ret;
--      int r = 0;
--      ssize_t i, len;
-       USBI_GET_CONTEXT(ctx);
-       usbi_dbg("");
 -
 -      usbi_dbg(" ");
--
--      if (!discdevs)
--              return LIBUSB_ERROR_NO_MEM;
 -
 -      ctx = usbi_get_context(ctx);
--
--      if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
--              /* backend provides hotplug support */
--              struct libusb_device *dev;
--
--              if (usbi_backend.hotplug_poll)
--                      usbi_backend.hotplug_poll();
--
--              usbi_mutex_lock(&ctx->usb_devs_lock);
-               list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
 -              for_each_device(ctx, dev) {
--                      discdevs = discovered_devs_append(discdevs, dev);
--
--                      if (!discdevs) {
--                              r = LIBUSB_ERROR_NO_MEM;
--                              break;
--                      }
--              }
--              usbi_mutex_unlock(&ctx->usb_devs_lock);
--      } else {
--              /* backend does not provide hotplug support */
--              r = usbi_backend.get_device_list(ctx, &discdevs);
--      }
--
--      if (r < 0) {
--              len = r;
--              goto out;
--      }
--
--      /* convert discovered_devs into a list */
-       len = discdevs->len;
-       ret = calloc(len + 1, sizeof(struct libusb_device *));
 -      len = (ssize_t)discdevs->len;
 -      ret = calloc((size_t)len + 1, sizeof(struct libusb_device *));
--      if (!ret) {
--              len = LIBUSB_ERROR_NO_MEM;
--              goto out;
--      }
--
--      ret[len] = NULL;
--      for (i = 0; i < len; i++) {
--              struct libusb_device *dev = discdevs->devices[i];
--              ret[i] = libusb_ref_device(dev);
--      }
--      *list = ret;
--
--out:
--      if (discdevs)
--              discovered_devs_free(discdevs);
--      return len;
--}
--
--/** \ingroup libusb_dev
-- * Frees a list of devices previously discovered using
-- * libusb_get_device_list(). If the unref_devices parameter is set, the
-- * reference count of each device in the list is decremented by 1.
-- * \param list the list to free
-- * \param unref_devices whether to unref the devices in the list
-- */
--void API_EXPORTED libusb_free_device_list(libusb_device **list,
--      int unref_devices)
--{
--      if (!list)
--              return;
--
--      if (unref_devices) {
--              int i = 0;
--              struct libusb_device *dev;
--
--              while ((dev = list[i++]) != NULL)
--                      libusb_unref_device(dev);
--      }
--      free(list);
--}
--
--/** \ingroup libusb_dev
-- * Get the number of the bus that a device is connected to.
-- * \param dev a device
-- * \returns the bus number
-- */
--uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
--{
--      return dev->bus_number;
--}
--
--/** \ingroup libusb_dev
-- * Get the number of the port that a device is connected to.
-- * Unless the OS does something funky, or you are hot-plugging USB extension cards,
-- * the port number returned by this call is usually guaranteed to be uniquely tied
-- * to a physical port, meaning that different devices plugged on the same physical
-- * port should return the same port number.
-- *
-- * But outside of this, there is no guarantee that the port number returned by this
-- * call will remain the same, or even match the order in which ports have been
-- * numbered by the HUB/HCD manufacturer.
-- *
-- * \param dev a device
-- * \returns the port number (0 if not available)
-- */
--uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
--{
--      return dev->port_number;
--}
--
--/** \ingroup libusb_dev
-- * Get the list of all port numbers from root for the specified device
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- * \param dev a device
-- * \param port_numbers the array that should contain the port numbers
-- * \param port_numbers_len the maximum length of the array. As per the USB 3.0
-- * specs, the current maximum limit for the depth is 7.
-- * \returns the number of elements filled
-- * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
-- */
--int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
-       uint8_t* port_numbers, int port_numbers_len)
 -      uint8_t *port_numbers, int port_numbers_len)
--{
--      int i = port_numbers_len;
--      struct libusb_context *ctx = DEVICE_CTX(dev);
--
--      if (port_numbers_len <= 0)
--              return LIBUSB_ERROR_INVALID_PARAM;
--
--      // HCDs can be listed as devices with port #0
--      while((dev) && (dev->port_number != 0)) {
--              if (--i < 0) {
--                      usbi_warn(ctx, "port numbers array is too small");
--                      return LIBUSB_ERROR_OVERFLOW;
--              }
--              port_numbers[i] = dev->port_number;
--              dev = dev->parent_dev;
--      }
--      if (i < port_numbers_len)
--              memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
--      return port_numbers_len - i;
--}
--
--/** \ingroup libusb_dev
-  * Deprecated please use libusb_get_port_numbers instead.
 - * \deprecated Please use \ref libusb_get_port_numbers() instead.
-- */
--int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
-       uint8_t* port_numbers, uint8_t port_numbers_len)
 -      uint8_t *port_numbers, uint8_t port_numbers_len)
--{
--      UNUSED(ctx);
--
--      return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
--}
--
--/** \ingroup libusb_dev
-- * Get the the parent from the specified device.
-- * \param dev a device
-- * \returns the device parent or NULL if not available
-- * You should issue a \ref libusb_get_device_list() before calling this
-- * function and make sure that you only access the parent before issuing
-- * \ref libusb_free_device_list(). The reason is that libusb currently does
-- * not maintain a permanent list of device instances, and therefore can
-  * only guarantee that parents are fully instantiated within a 
 - * only guarantee that parents are fully instantiated within a
-- * libusb_get_device_list() - libusb_free_device_list() block.
-- */
--DEFAULT_VISIBILITY
--libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
--{
--      return dev->parent_dev;
--}
--
--/** \ingroup libusb_dev
-- * Get the address of the device on the bus it is connected to.
-- * \param dev a device
-- * \returns the device address
-- */
--uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
--{
--      return dev->device_address;
--}
--
--/** \ingroup libusb_dev
-- * Get the negotiated connection speed for a device.
-- * \param dev a device
-- * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
-- * the OS doesn't know or doesn't support returning the negotiated speed.
-- */
--int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
--{
--      return dev->speed;
--}
--
--static const struct libusb_endpoint_descriptor *find_endpoint(
--      struct libusb_config_descriptor *config, unsigned char endpoint)
--{
--      int iface_idx;
--      for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
--              const struct libusb_interface *iface = &config->interface[iface_idx];
--              int altsetting_idx;
--
--              for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
--                              altsetting_idx++) {
--                      const struct libusb_interface_descriptor *altsetting
--                              = &iface->altsetting[altsetting_idx];
--                      int ep_idx;
--
--                      for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
--                              const struct libusb_endpoint_descriptor *ep =
--                                      &altsetting->endpoint[ep_idx];
--                              if (ep->bEndpointAddress == endpoint)
--                                      return ep;
--                      }
--              }
--      }
--      return NULL;
--}
--
--/** \ingroup libusb_dev
-- * Convenience function to retrieve the wMaxPacketSize value for a particular
-- * endpoint in the active device configuration.
-- *
-- * This function was originally intended to be of assistance when setting up
-- * isochronous transfers, but a design mistake resulted in this function
-- * instead. It simply returns the wMaxPacketSize value without considering
-- * its contents. If you're dealing with isochronous transfers, you probably
-- * want libusb_get_max_iso_packet_size() instead.
-- *
-- * \param dev a device
-- * \param endpoint address of the endpoint in question
-- * \returns the wMaxPacketSize value
-- * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
-- * \returns LIBUSB_ERROR_OTHER on other failure
-- */
--int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
--      unsigned char endpoint)
--{
--      struct libusb_config_descriptor *config;
--      const struct libusb_endpoint_descriptor *ep;
--      int r;
--
--      r = libusb_get_active_config_descriptor(dev, &config);
--      if (r < 0) {
--              usbi_err(DEVICE_CTX(dev),
--                      "could not retrieve active config descriptor");
--              return LIBUSB_ERROR_OTHER;
--      }
--
--      ep = find_endpoint(config, endpoint);
--      if (!ep) {
--              r = LIBUSB_ERROR_NOT_FOUND;
--              goto out;
--      }
--
--      r = ep->wMaxPacketSize;
--
--out:
--      libusb_free_config_descriptor(config);
--      return r;
--}
--
--/** \ingroup libusb_dev
-- * Calculate the maximum packet size which a specific endpoint is capable is
-- * sending or receiving in the duration of 1 microframe
-- *
-- * Only the active configuration is examined. The calculation is based on the
-- * wMaxPacketSize field in the endpoint descriptor as described in section
-- * 9.6.6 in the USB 2.0 specifications.
-- *
-- * If acting on an isochronous or interrupt endpoint, this function will
-- * multiply the value found in bits 0:10 by the number of transactions per
-- * microframe (determined by bits 11:12). Otherwise, this function just
-  * returns the numeric value found in bits 0:10.
 - * returns the numeric value found in bits 0:10. For USB 3.0 device, it
 - * will attempts to retrieve the Endpoint Companion Descriptor to return
 - * wBytesPerInterval.
-- *
-- * This function is useful for setting up isochronous transfers, for example
-- * you might pass the return value from this function to
-- * libusb_set_iso_packet_lengths() in order to set the length field of every
-- * isochronous packet in a transfer.
-- *
-- * Since v1.0.3.
-- *
-- * \param dev a device
-- * \param endpoint address of the endpoint in question
-- * \returns the maximum packet size which can be sent/received on this endpoint
-- * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
-- * \returns LIBUSB_ERROR_OTHER on other failure
-- */
--int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
--      unsigned char endpoint)
--{
--      struct libusb_config_descriptor *config;
--      const struct libusb_endpoint_descriptor *ep;
-       enum libusb_transfer_type ep_type;
 -      struct libusb_ss_endpoint_companion_descriptor *ss_ep_cmp;
 -      enum libusb_endpoint_transfer_type ep_type;
--      uint16_t val;
--      int r;
 -      int speed;
--
--      r = libusb_get_active_config_descriptor(dev, &config);
--      if (r < 0) {
--              usbi_err(DEVICE_CTX(dev),
--                      "could not retrieve active config descriptor");
--              return LIBUSB_ERROR_OTHER;
--      }
--
--      ep = find_endpoint(config, endpoint);
--      if (!ep) {
--              r = LIBUSB_ERROR_NOT_FOUND;
--              goto out;
--      }
--
-       val = ep->wMaxPacketSize;
-       ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
 -      speed = libusb_get_device_speed(dev);
 -      if (speed >= LIBUSB_SPEED_SUPER) {
 -              r = libusb_get_ss_endpoint_companion_descriptor(dev->ctx, ep, &ss_ep_cmp);
 -              if (r == LIBUSB_SUCCESS) {
 -                      r = ss_ep_cmp->wBytesPerInterval;
 -                      libusb_free_ss_endpoint_companion_descriptor(ss_ep_cmp);
 -              }
 -      }
--
-       r = val & 0x07ff;
-       if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
-                       || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
-               r *= (1 + ((val >> 11) & 3));
 -      /* If the device isn't a SuperSpeed device or retrieving the SS endpoint didn't worked. */
 -      if (speed < LIBUSB_SPEED_SUPER || r < 0) {
 -              val = ep->wMaxPacketSize;
 -              ep_type = (enum libusb_endpoint_transfer_type) (ep->bmAttributes & 0x3);
 -
 -              r = val & 0x07ff;
 -              if (ep_type == LIBUSB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS
 -                  || ep_type == LIBUSB_ENDPOINT_TRANSFER_TYPE_INTERRUPT)
 -                      r *= (1 + ((val >> 11) & 3));
 -      }
--
--out:
--      libusb_free_config_descriptor(config);
--      return r;
--}
--
--/** \ingroup libusb_dev
-- * Increment the reference count of a device.
-- * \param dev the device to reference
-- * \returns the same device
-- */
--DEFAULT_VISIBILITY
--libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
--{
--      usbi_mutex_lock(&dev->lock);
--      dev->refcnt++;
--      usbi_mutex_unlock(&dev->lock);
--      return dev;
--}
--
--/** \ingroup libusb_dev
-- * Decrement the reference count of a device. If the decrement operation
-- * causes the reference count to reach zero, the device shall be destroyed.
-- * \param dev the device to unreference
-- */
--void API_EXPORTED libusb_unref_device(libusb_device *dev)
--{
--      int refcnt;
--
--      if (!dev)
--              return;
--
--      usbi_mutex_lock(&dev->lock);
--      refcnt = --dev->refcnt;
--      usbi_mutex_unlock(&dev->lock);
--
--      if (refcnt == 0) {
--              usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
--
--              libusb_unref_device(dev->parent_dev);
--
--              if (usbi_backend.destroy_device)
--                      usbi_backend.destroy_device(dev);
--
--              if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
--                      /* backend does not support hotplug */
--                      usbi_disconnect_device(dev);
--              }
--
--              usbi_mutex_destroy(&dev->lock);
--              free(dev);
--      }
--}
--
- /*
-  * Signal the event pipe so that the event handling thread will be
-  * interrupted to process an internal event.
 -/** \ingroup libusb_dev
 - * Wrap a platform-specific system device handle and obtain a libusb device
 - * handle for the underlying device. The handle allows you to use libusb to
 - * perform I/O on the device in question.
 - *
 - * Must call libusb_set_option(NULL, LIBUSB_OPTION_WEAK_AUTHORITY)
 - * before libusb_init if don't have authority to access the usb device directly.
 - *
 - * On Linux, the system device handle must be a valid file descriptor opened
 - * on the device node.
 - *
 - * The system device handle must remain open until libusb_close() is called.
 - * The system device handle will not be closed by libusb_close().
 - *
 - * Internally, this function creates a temporary device and makes it
 - * available to you through libusb_get_device(). This device is destroyed
 - * during libusb_close(). The device shall not be opened through libusb_open().
 - *
 - * This is a non-blocking function; no requests are sent over the bus.
 - *
 - * \param ctx the context to operate on, or NULL for the default context
 - * \param sys_dev the platform-specific system device handle
 - * \param dev_handle output location for the returned device handle pointer. Only
 - * populated when the return code is 0.
 - * \returns 0 on success
 - * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
 - * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
 - * \returns LIBUSB_ERROR_NOT_SUPPORTED if the operation is not supported on this
 - * platform
 - * \returns another LIBUSB_ERROR code on other failure
-- */
- int usbi_signal_event(struct libusb_context *ctx)
 -int API_EXPORTED libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev,
 -      libusb_device_handle **dev_handle)
--{
-       unsigned char dummy = 1;
-       ssize_t r;
 -      struct libusb_device_handle *_dev_handle;
 -      size_t priv_size = usbi_backend.device_handle_priv_size;
 -      int r;
--
-       /* write some data on event pipe to interrupt event handlers */
-       r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy));
-       if (r != sizeof(dummy)) {
-               usbi_warn(ctx, "internal signalling write failed");
-               return LIBUSB_ERROR_IO;
-       }
 -      usbi_dbg("wrap_sys_device 0x%" PRIxPTR, (uintptr_t)sys_dev);
--
-       return 0;
- }
 -      ctx = usbi_get_context(ctx);
--
- /*
-  * Clear the event pipe so that the event handling will no longer be
-  * interrupted.
-  */
- int usbi_clear_event(struct libusb_context *ctx)
- {
-       unsigned char dummy;
-       ssize_t r;
 -      if (!usbi_backend.wrap_sys_device)
 -              return LIBUSB_ERROR_NOT_SUPPORTED;
--
-       /* read some data on event pipe to clear it */
-       r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy));
-       if (r != sizeof(dummy)) {
-               usbi_warn(ctx, "internal signalling read failed");
-               return LIBUSB_ERROR_IO;
 -      _dev_handle = calloc(1, PTR_ALIGN(sizeof(*_dev_handle)) + priv_size);
 -      if (!_dev_handle)
 -              return LIBUSB_ERROR_NO_MEM;
 -
 -      usbi_mutex_init(&_dev_handle->lock);
 -
 -      r = usbi_backend.wrap_sys_device(ctx, _dev_handle, sys_dev);
 -      if (r < 0) {
 -              usbi_dbg("wrap_sys_device 0x%" PRIxPTR " returns %d", (uintptr_t)sys_dev, r);
 -              usbi_mutex_destroy(&_dev_handle->lock);
 -              free(_dev_handle);
 -              return r;
--      }
 -
 -      usbi_mutex_lock(&ctx->open_devs_lock);
 -      list_add(&_dev_handle->list, &ctx->open_devs);
 -      usbi_mutex_unlock(&ctx->open_devs_lock);
 -      *dev_handle = _dev_handle;
--
--      return 0;
--}
--
--/** \ingroup libusb_dev
-- * Open a device and obtain a device handle. A handle allows you to perform
-- * I/O on the device in question.
-- *
-- * Internally, this function adds a reference to the device and makes it
-- * available to you through libusb_get_device(). This reference is removed
-- * during libusb_close().
-- *
-- * This is a non-blocking function; no requests are sent over the bus.
-- *
-- * \param dev the device to open
-- * \param dev_handle output location for the returned device handle pointer. Only
-- * populated when the return code is 0.
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
-- * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- */
--int API_EXPORTED libusb_open(libusb_device *dev,
--      libusb_device_handle **dev_handle)
--{
--      struct libusb_context *ctx = DEVICE_CTX(dev);
--      struct libusb_device_handle *_dev_handle;
--      size_t priv_size = usbi_backend.device_handle_priv_size;
--      int r;
--      usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
--
--      if (!dev->attached) {
--              return LIBUSB_ERROR_NO_DEVICE;
--      }
--
-       _dev_handle = malloc(sizeof(*_dev_handle) + priv_size);
 -      _dev_handle = calloc(1, PTR_ALIGN(sizeof(*_dev_handle)) + priv_size);
--      if (!_dev_handle)
--              return LIBUSB_ERROR_NO_MEM;
--
-       r = usbi_mutex_init(&_dev_handle->lock);
-       if (r) {
-               free(_dev_handle);
-               return LIBUSB_ERROR_OTHER;
-       }
 -      usbi_mutex_init(&_dev_handle->lock);
--
--      _dev_handle->dev = libusb_ref_device(dev);
-       _dev_handle->auto_detach_kernel_driver = 0;
-       _dev_handle->claimed_interfaces = 0;
-       memset(&_dev_handle->os_priv, 0, priv_size);
--
--      r = usbi_backend.open(_dev_handle);
--      if (r < 0) {
--              usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
--              libusb_unref_device(dev);
--              usbi_mutex_destroy(&_dev_handle->lock);
--              free(_dev_handle);
--              return r;
--      }
--
--      usbi_mutex_lock(&ctx->open_devs_lock);
--      list_add(&_dev_handle->list, &ctx->open_devs);
--      usbi_mutex_unlock(&ctx->open_devs_lock);
--      *dev_handle = _dev_handle;
--
--      return 0;
--}
--
--/** \ingroup libusb_dev
-- * Convenience function for finding a device with a particular
-- * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
-- * for those scenarios where you are using libusb to knock up a quick test
-- * application - it allows you to avoid calling libusb_get_device_list() and
-- * worrying about traversing/freeing the list.
-- *
-- * This function has limitations and is hence not intended for use in real
-- * applications: if multiple devices have the same IDs it will only
-- * give you the first one, etc.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param vendor_id the idVendor value to search for
-- * \param product_id the idProduct value to search for
-- * \returns a device handle for the first found device, or NULL on error
-- * or if the device could not be found. */
--DEFAULT_VISIBILITY
--libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
--      libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
--{
--      struct libusb_device **devs;
--      struct libusb_device *found = NULL;
--      struct libusb_device *dev;
--      struct libusb_device_handle *dev_handle = NULL;
--      size_t i = 0;
--      int r;
--
--      if (libusb_get_device_list(ctx, &devs) < 0)
--              return NULL;
--
--      while ((dev = devs[i++]) != NULL) {
--              struct libusb_device_descriptor desc;
--              r = libusb_get_device_descriptor(dev, &desc);
--              if (r < 0)
--                      goto out;
--              if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
--                      found = dev;
--                      break;
--              }
--      }
--
--      if (found) {
--              r = libusb_open(found, &dev_handle);
--              if (r < 0)
--                      dev_handle = NULL;
--      }
--
--out:
--      libusb_free_device_list(devs, 1);
--      return dev_handle;
--}
--
--static void do_close(struct libusb_context *ctx,
--      struct libusb_device_handle *dev_handle)
--{
--      struct usbi_transfer *itransfer;
--      struct usbi_transfer *tmp;
--
--      /* remove any transfers in flight that are for this device */
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
--
--      /* safe iteration because transfers may be being deleted */
-       list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
 -      for_each_transfer_safe(ctx, itransfer, tmp) {
--              struct libusb_transfer *transfer =
--                      USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--
--              if (transfer->dev_handle != dev_handle)
--                      continue;
--
--              usbi_mutex_lock(&itransfer->lock);
--              if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
--                      usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
--
--                      if (itransfer->state_flags & USBI_TRANSFER_CANCELLING)
--                              usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
--                      else
--                              usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
--              }
--              usbi_mutex_unlock(&itransfer->lock);
--
--              /* remove from the list of in-flight transfers and make sure
--               * we don't accidentally use the device handle in the future
--               * (or that such accesses will be easily caught and identified as a crash)
--               */
--              list_del(&itransfer->list);
--              transfer->dev_handle = NULL;
--
--              /* it is up to the user to free up the actual transfer struct.  this is
--               * just making sure that we don't attempt to process the transfer after
--               * the device handle is invalid
--               */
--              usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
--                       transfer, dev_handle);
--      }
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
--
--      usbi_mutex_lock(&ctx->open_devs_lock);
--      list_del(&dev_handle->list);
--      usbi_mutex_unlock(&ctx->open_devs_lock);
--
--      usbi_backend.close(dev_handle);
--      libusb_unref_device(dev_handle->dev);
--      usbi_mutex_destroy(&dev_handle->lock);
--      free(dev_handle);
--}
--
--/** \ingroup libusb_dev
-- * Close a device handle. Should be called on all open handles before your
-- * application exits.
-- *
-- * Internally, this function destroys the reference that was added by
-- * libusb_open() on the given device.
-- *
-- * This is a non-blocking function; no requests are sent over the bus.
-- *
-- * \param dev_handle the device handle to close
-- */
--void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
--{
--      struct libusb_context *ctx;
 -      unsigned int event_flags;
--      int handling_events;
-       int pending_events;
--
--      if (!dev_handle)
--              return;
-       usbi_dbg("");
 -      usbi_dbg(" ");
--
--      ctx = HANDLE_CTX(dev_handle);
--      handling_events = usbi_handling_events(ctx);
--
--      /* Similarly to libusb_open(), we want to interrupt all event handlers
--       * at this point. More importantly, we want to perform the actual close of
--       * the device while holding the event handling lock (preventing any other
--       * thread from doing event handling) because we will be removing a file
--       * descriptor from the polling loop. If this is being called by the current
--       * event handler, we can bypass the interruption code because we already
--       * hold the event handling lock. */
--
--      if (!handling_events) {
--              /* Record that we are closing a device.
--               * Only signal an event if there are no prior pending events. */
--              usbi_mutex_lock(&ctx->event_data_lock);
-               pending_events = usbi_pending_events(ctx);
-               ctx->device_close++;
-               if (!pending_events)
-                       usbi_signal_event(ctx);
 -              event_flags = ctx->event_flags;
 -              if (!ctx->device_close++)
 -                      ctx->event_flags |= USBI_EVENT_DEVICE_CLOSE;
 -              if (!event_flags)
 -                      usbi_signal_event(&ctx->event);
--              usbi_mutex_unlock(&ctx->event_data_lock);
--
--              /* take event handling lock */
--              libusb_lock_events(ctx);
--      }
--
--      /* Close the device */
--      do_close(ctx, dev_handle);
--
--      if (!handling_events) {
--              /* We're done with closing this device.
--               * Clear the event pipe if there are no further pending events. */
--              usbi_mutex_lock(&ctx->event_data_lock);
-               ctx->device_close--;
-               pending_events = usbi_pending_events(ctx);
-               if (!pending_events)
-                       usbi_clear_event(ctx);
 -              if (!--ctx->device_close)
 -                      ctx->event_flags &= ~USBI_EVENT_DEVICE_CLOSE;
 -              if (!ctx->event_flags)
 -                      usbi_clear_event(&ctx->event);
--              usbi_mutex_unlock(&ctx->event_data_lock);
--
--              /* Release event handling lock and wake up event waiters */
--              libusb_unlock_events(ctx);
--      }
--}
--
--/** \ingroup libusb_dev
-- * Get the underlying device for a device handle. This function does not modify
-- * the reference count of the returned device, so do not feel compelled to
-- * unreference it when you are done.
-- * \param dev_handle a device handle
-- * \returns the underlying device
-- */
--DEFAULT_VISIBILITY
--libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
--{
--      return dev_handle->dev;
--}
--
--/** \ingroup libusb_dev
-- * Determine the bConfigurationValue of the currently active configuration.
-- *
-- * You could formulate your own control request to obtain this information,
-- * but this function has the advantage that it may be able to retrieve the
-- * information from operating system caches (no I/O involved).
-- *
-- * If the OS does not cache this information, then this function will block
-- * while a control transfer is submitted to retrieve the information.
-- *
-- * This function will return a value of 0 in the <tt>config</tt> output
-- * parameter if the device is in unconfigured state.
-- *
-- * \param dev_handle a device handle
-- * \param config output location for the bConfigurationValue of the active
-- * configuration (only valid for return code 0)
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- */
--int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
--      int *config)
--{
--      int r = LIBUSB_ERROR_NOT_SUPPORTED;
 -      uint8_t tmp = 0;
--
-       usbi_dbg("");
 -      usbi_dbg(" ");
--      if (usbi_backend.get_configuration)
-               r = usbi_backend.get_configuration(dev_handle, config);
 -              r = usbi_backend.get_configuration(dev_handle, &tmp);
--
--      if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
-               uint8_t tmp = 0;
--              usbi_dbg("falling back to control message");
--              r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
--                      LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
-               if (r == 0) {
 -              if (r == 1) {
 -                      r = 0;
 -              } else if (r == 0) {
--                      usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?");
--                      r = LIBUSB_ERROR_IO;
-               } else if (r == 1) {
-                       r = 0;
-                       *config = tmp;
--              } else {
--                      usbi_dbg("control failed, error %d", r);
--              }
--      }
--
-       if (r == 0)
-               usbi_dbg("active config %d", *config);
 -      if (r == 0) {
 -              usbi_dbg("active config %u", tmp);
 -              *config = (int)tmp;
 -      }
--
--      return r;
--}
--
--/** \ingroup libusb_dev
-- * Set the active configuration for a device.
-- *
-- * The operating system may or may not have already set an active
-- * configuration on the device. It is up to your application to ensure the
-- * correct configuration is selected before you attempt to claim interfaces
-- * and perform other operations.
-- *
-- * If you call this function on a device already configured with the selected
-- * configuration, then this function will act as a lightweight device reset:
-- * it will issue a SET_CONFIGURATION request using the current configuration,
-- * causing most USB-related device state to be reset (altsetting reset to zero,
-- * endpoint halts cleared, toggles reset).
 - *
 - * Not all backends support setting the configuration from user space, which
 - * will be indicated by the return code LIBUSB_ERROR_NOT_SUPPORTED. As this
 - * suggests that the platform is handling the device configuration itself,
 - * this error should generally be safe to ignore.
-- *
-- * You cannot change/reset configuration if your application has claimed
-- * interfaces. It is advised to set the desired configuration before claiming
-- * interfaces.
-- *
-- * Alternatively you can call libusb_release_interface() first. Note if you
-- * do things this way you must ensure that auto_detach_kernel_driver for
-- * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
-- * release the interface(s).
-- *
-- * You cannot change/reset configuration if other applications or drivers have
-- * claimed interfaces.
-- *
-- * A configuration value of -1 will put the device in unconfigured state.
-- * The USB specifications state that a configuration value of 0 does this,
-- * however buggy devices exist which actually have a configuration 0.
-- *
-- * You should always use this function rather than formulating your own
-- * SET_CONFIGURATION control request. This is because the underlying operating
-- * system needs to know when such changes happen.
-- *
-- * This is a blocking function.
-- *
-- * \param dev_handle a device handle
-- * \param configuration the bConfigurationValue of the configuration you
-- * wish to activate, or -1 if you wish to put the device in an unconfigured
-- * state
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
-- * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
 - * \returns LIBUSB_ERROR_NOT_SUPPORTED if setting or changing the configuration
 - * is not supported by the backend
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- * \see libusb_set_auto_detach_kernel_driver()
-- */
--int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
--      int configuration)
--{
--      usbi_dbg("configuration %d", configuration);
 -      if (configuration < -1 || configuration > (int)UINT8_MAX)
 -              return LIBUSB_ERROR_INVALID_PARAM;
--      return usbi_backend.set_configuration(dev_handle, configuration);
--}
--
--/** \ingroup libusb_dev
-- * Claim an interface on a given device handle. You must claim the interface
-- * you wish to use before you can perform I/O on any of its endpoints.
-- *
-- * It is legal to attempt to claim an already-claimed interface, in which
-- * case libusb just returns 0 without doing anything.
-- *
-- * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
-- * will be detached if necessary, on failure the detach error is returned.
-- *
-- * Claiming of interfaces is a purely logical operation; it does not cause
-- * any requests to be sent over the bus. Interface claiming is used to
-- * instruct the underlying operating system that your application wishes
-- * to take ownership of the interface.
-- *
-- * This is a non-blocking function.
-- *
-- * \param dev_handle a device handle
-- * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
-- * wish to claim
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
-- * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
-- * interface
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns a LIBUSB_ERROR code on other failure
-- * \see libusb_set_auto_detach_kernel_driver()
-- */
--int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
--      int interface_number)
--{
--      int r = 0;
--
--      usbi_dbg("interface %d", interface_number);
-       if (interface_number >= USB_MAXINTERFACES)
 -      if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
--              return LIBUSB_ERROR_INVALID_PARAM;
--
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      usbi_mutex_lock(&dev_handle->lock);
-       if (dev_handle->claimed_interfaces & (1 << interface_number))
 -      if (dev_handle->claimed_interfaces & (1U << interface_number))
--              goto out;
--
-       r = usbi_backend.claim_interface(dev_handle, interface_number);
 -      r = usbi_backend.claim_interface(dev_handle, (uint8_t)interface_number);
--      if (r == 0)
-               dev_handle->claimed_interfaces |= 1 << interface_number;
 -              dev_handle->claimed_interfaces |= 1U << interface_number;
--
--out:
--      usbi_mutex_unlock(&dev_handle->lock);
--      return r;
--}
--
--/** \ingroup libusb_dev
-- * Release an interface previously claimed with libusb_claim_interface(). You
-- * should release all claimed interfaces before closing a device handle.
-- *
-- * This is a blocking function. A SET_INTERFACE control request will be sent
-- * to the device, resetting interface state to the first alternate setting.
-- *
-- * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
-- * driver will be re-attached after releasing the interface.
-- *
-- * \param dev_handle a device handle
-- * \param interface_number the <tt>bInterfaceNumber</tt> of the
-- * previously-claimed interface
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- * \see libusb_set_auto_detach_kernel_driver()
-- */
--int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
--      int interface_number)
--{
--      int r;
--
--      usbi_dbg("interface %d", interface_number);
-       if (interface_number >= USB_MAXINTERFACES)
 -      if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
--              return LIBUSB_ERROR_INVALID_PARAM;
--
--      usbi_mutex_lock(&dev_handle->lock);
-       if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
 -      if (!(dev_handle->claimed_interfaces & (1U << interface_number))) {
--              r = LIBUSB_ERROR_NOT_FOUND;
--              goto out;
--      }
--
-       r = usbi_backend.release_interface(dev_handle, interface_number);
 -      r = usbi_backend.release_interface(dev_handle, (uint8_t)interface_number);
--      if (r == 0)
-               dev_handle->claimed_interfaces &= ~(1 << interface_number);
 -              dev_handle->claimed_interfaces &= ~(1U << interface_number);
--
--out:
--      usbi_mutex_unlock(&dev_handle->lock);
--      return r;
--}
--
--/** \ingroup libusb_dev
-- * Activate an alternate setting for an interface. The interface must have
-- * been previously claimed with libusb_claim_interface().
-- *
-- * You should always use this function rather than formulating your own
-- * SET_INTERFACE control request. This is because the underlying operating
-- * system needs to know when such changes happen.
-- *
-- * This is a blocking function.
-- *
-- * \param dev_handle a device handle
-- * \param interface_number the <tt>bInterfaceNumber</tt> of the
-- * previously-claimed interface
-- * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
-- * setting to activate
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
-- * requested alternate setting does not exist
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- */
--int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
--      int interface_number, int alternate_setting)
--{
--      usbi_dbg("interface %d altsetting %d",
--              interface_number, alternate_setting);
-       if (interface_number >= USB_MAXINTERFACES)
 -      if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
 -              return LIBUSB_ERROR_INVALID_PARAM;
 -      if (alternate_setting < 0 || alternate_setting > (int)UINT8_MAX)
--              return LIBUSB_ERROR_INVALID_PARAM;
--
--      usbi_mutex_lock(&dev_handle->lock);
--      if (!dev_handle->dev->attached) {
--              usbi_mutex_unlock(&dev_handle->lock);
--              return LIBUSB_ERROR_NO_DEVICE;
--      }
--
-       if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
 -      if (!(dev_handle->claimed_interfaces & (1U << interface_number))) {
--              usbi_mutex_unlock(&dev_handle->lock);
--              return LIBUSB_ERROR_NOT_FOUND;
--      }
--      usbi_mutex_unlock(&dev_handle->lock);
--
-       return usbi_backend.set_interface_altsetting(dev_handle, interface_number,
-               alternate_setting);
 -      return usbi_backend.set_interface_altsetting(dev_handle,
 -              (uint8_t)interface_number, (uint8_t)alternate_setting);
--}
--
--/** \ingroup libusb_dev
-- * Clear the halt/stall condition for an endpoint. Endpoints with halt status
-- * are unable to receive or transmit data until the halt condition is stalled.
-- *
-- * You should cancel all pending transfers before attempting to clear the halt
-- * condition.
-- *
-- * This is a blocking function.
-- *
-- * \param dev_handle a device handle
-- * \param endpoint the endpoint to clear halt status
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- */
--int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
--      unsigned char endpoint)
--{
--      usbi_dbg("endpoint %x", endpoint);
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      return usbi_backend.clear_halt(dev_handle, endpoint);
--}
--
--/** \ingroup libusb_dev
-- * Perform a USB port reset to reinitialize a device. The system will attempt
-- * to restore the previous configuration and alternate settings after the
-- * reset has completed.
-- *
-- * If the reset fails, the descriptors change, or the previous state cannot be
-- * restored, the device will appear to be disconnected and reconnected. This
-- * means that the device handle is no longer valid (you should close it) and
-- * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
-- * when this is the case.
-- *
-- * This is a blocking function which usually incurs a noticeable delay.
-- *
-- * \param dev_handle a handle of the device to reset
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
-- * device has been disconnected
-- * \returns another LIBUSB_ERROR code on other failure
-- */
--int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
--{
-       usbi_dbg("");
 -      usbi_dbg(" ");
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
-       return usbi_backend.reset_device(dev_handle);
 -      if (usbi_backend.reset_device)
 -              return usbi_backend.reset_device(dev_handle);
 -      else
 -              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_asyncio
-- * Allocate up to num_streams usb bulk streams on the specified endpoints. This
-- * function takes an array of endpoints rather then a single endpoint because
-- * some protocols require that endpoints are setup with similar stream ids.
-- * All endpoints passed in must belong to the same interface.
-- *
-- * Note this function may return less streams then requested. Also note that the
-- * same number of streams are allocated for each endpoint in the endpoint array.
-- *
-- * Stream id 0 is reserved, and should not be used to communicate with devices.
-- * If libusb_alloc_streams() returns with a value of N, you may use stream ids
-- * 1 to N.
-- *
-- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
-- *
-- * \param dev_handle a device handle
-- * \param num_streams number of streams to try to allocate
-- * \param endpoints array of endpoints to allocate streams on
-- * \param num_endpoints length of the endpoints array
-- * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
--      uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
--{
-       usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
 -      usbi_dbg("streams %u eps %d", (unsigned)num_streams, num_endpoints);
 -
 -      if (!num_streams || !endpoints || num_endpoints <= 0)
 -              return LIBUSB_ERROR_INVALID_PARAM;
--
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      if (usbi_backend.alloc_streams)
--              return usbi_backend.alloc_streams(dev_handle, num_streams, endpoints,
--                                                 num_endpoints);
--      else
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_asyncio
-- * Free usb bulk streams allocated with libusb_alloc_streams().
-- *
-- * Note streams are automatically free-ed when releasing an interface.
-- *
-- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
-- *
-- * \param dev_handle a device handle
-- * \param endpoints array of endpoints to free streams on
-- * \param num_endpoints length of the endpoints array
-- * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
--      unsigned char *endpoints, int num_endpoints)
--{
--      usbi_dbg("eps %d", num_endpoints);
 -
 -      if (!endpoints || num_endpoints <= 0)
 -              return LIBUSB_ERROR_INVALID_PARAM;
--
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      if (usbi_backend.free_streams)
--              return usbi_backend.free_streams(dev_handle, endpoints,
--                                                num_endpoints);
--      else
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_asyncio
-- * Attempts to allocate a block of persistent DMA memory suitable for transfers
-- * against the given device. If successful, will return a block of memory
-- * that is suitable for use as "buffer" in \ref libusb_transfer against this
-- * device. Using this memory instead of regular memory means that the host
-- * controller can use DMA directly into the buffer to increase performance, and
-- * also that transfers can no longer fail due to kernel memory fragmentation.
-- *
-- * Note that this means you should not modify this memory (or even data on
-- * the same cache lines) when a transfer is in progress, although it is legal
-- * to have several transfers going on within the same memory block.
-- *
-  * Will return NULL on failure. Many systems do not support such zerocopy
 - * Will return NULL on failure. Many systems do not support such zero-copy
-- * and will always return NULL. Memory allocated with this function must be
-- * freed with \ref libusb_dev_mem_free. Specifically, this means that the
-- * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
-- * with this function.
-- *
-- * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
-- *
-- * \param dev_handle a device handle
-- * \param length size of desired data buffer
-- * \returns a pointer to the newly allocated memory, or NULL on failure
-- */
--DEFAULT_VISIBILITY
--unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
--        size_t length)
--{
--      if (!dev_handle->dev->attached)
--              return NULL;
--
--      if (usbi_backend.dev_mem_alloc)
--              return usbi_backend.dev_mem_alloc(dev_handle, length);
--      else
--              return NULL;
--}
--
--/** \ingroup libusb_asyncio
-- * Free device memory allocated with libusb_dev_mem_alloc().
-- *
-- * \param dev_handle a device handle
-- * \param buffer pointer to the previously allocated memory
-- * \param length size of previously allocated memory
-- * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
--      unsigned char *buffer, size_t length)
--{
--      if (usbi_backend.dev_mem_free)
--              return usbi_backend.dev_mem_free(dev_handle, buffer, length);
--      else
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_dev
-- * Determine if a kernel driver is active on an interface. If a kernel driver
-- * is active, you cannot claim the interface, and libusb will be unable to
-- * perform I/O.
-- *
-- * This functionality is not available on Windows.
-- *
-- * \param dev_handle a device handle
-- * \param interface_number the interface to check
-- * \returns 0 if no kernel driver is active
-- * \returns 1 if a kernel driver is active
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
-- * is not available
-- * \returns another LIBUSB_ERROR code on other failure
-- * \see libusb_detach_kernel_driver()
-- */
--int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
--      int interface_number)
--{
--      usbi_dbg("interface %d", interface_number);
 -
 -      if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
 -              return LIBUSB_ERROR_INVALID_PARAM;
--
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      if (usbi_backend.kernel_driver_active)
-               return usbi_backend.kernel_driver_active(dev_handle, interface_number);
 -              return usbi_backend.kernel_driver_active(dev_handle, (uint8_t)interface_number);
--      else
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_dev
-- * Detach a kernel driver from an interface. If successful, you will then be
-- * able to claim the interface and perform I/O.
-- *
-- * This functionality is not available on Darwin or Windows.
-- *
-- * Note that libusb itself also talks to the device through a special kernel
-- * driver, if this driver is already attached to the device, this call will
-- * not detach it and return LIBUSB_ERROR_NOT_FOUND.
-- *
-- * \param dev_handle a device handle
-- * \param interface_number the interface to detach the driver from
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
-- * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
-- * is not available
-- * \returns another LIBUSB_ERROR code on other failure
-- * \see libusb_kernel_driver_active()
-- */
--int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
--      int interface_number)
--{
--      usbi_dbg("interface %d", interface_number);
 -
 -      if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
 -              return LIBUSB_ERROR_INVALID_PARAM;
--
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      if (usbi_backend.detach_kernel_driver)
-               return usbi_backend.detach_kernel_driver(dev_handle, interface_number);
 -              return usbi_backend.detach_kernel_driver(dev_handle, (uint8_t)interface_number);
--      else
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_dev
-- * Re-attach an interface's kernel driver, which was previously detached
-- * using libusb_detach_kernel_driver(). This call is only effective on
-- * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
-- *
-- * This functionality is not available on Darwin or Windows.
-- *
-- * \param dev_handle a device handle
-- * \param interface_number the interface to attach the driver from
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
-- * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
-- * is not available
-- * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
-- * interface is claimed by a program or driver
-- * \returns another LIBUSB_ERROR code on other failure
-- * \see libusb_kernel_driver_active()
-- */
--int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
--      int interface_number)
--{
--      usbi_dbg("interface %d", interface_number);
 -
 -      if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
 -              return LIBUSB_ERROR_INVALID_PARAM;
--
--      if (!dev_handle->dev->attached)
--              return LIBUSB_ERROR_NO_DEVICE;
--
--      if (usbi_backend.attach_kernel_driver)
-               return usbi_backend.attach_kernel_driver(dev_handle, interface_number);
 -              return usbi_backend.attach_kernel_driver(dev_handle, (uint8_t)interface_number);
--      else
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--/** \ingroup libusb_dev
-- * Enable/disable libusb's automatic kernel driver detachment. When this is
-- * enabled libusb will automatically detach the kernel driver on an interface
-- * when claiming the interface, and attach it when releasing the interface.
-- *
-- * Automatic kernel driver detachment is disabled on newly opened device
-- * handles by default.
-- *
-- * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
-- * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
-- * continue as if this function was never called.
-- *
-- * \param dev_handle a device handle
-- * \param enable whether to enable or disable auto kernel driver detachment
-- *
-- * \returns LIBUSB_SUCCESS on success
-- * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
-- * is not available
-- * \see libusb_claim_interface()
-- * \see libusb_release_interface()
-- * \see libusb_set_configuration()
-- */
--int API_EXPORTED libusb_set_auto_detach_kernel_driver(
--      libusb_device_handle *dev_handle, int enable)
--{
--      if (!(usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--
--      dev_handle->auto_detach_kernel_driver = enable;
--      return LIBUSB_SUCCESS;
--}
--
--/** \ingroup libusb_lib
-- * \deprecated Use libusb_set_option() instead using the
-- * \ref LIBUSB_OPTION_LOG_LEVEL option.
-- */
--void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
--{
--#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      if (!ctx->debug_fixed) {
--              level = CLAMP(level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
--              ctx->debug = (enum libusb_log_level)level;
--      }
--#else
--      UNUSED(ctx);
--      UNUSED(level);
 -#endif
 -}
 -
 -/** \ingroup libusb_lib
 - * Set log handler.
 - *
 - * libusb will redirect its log messages to the provided callback function.
 - * libusb supports redirection of per context and global log messages.
 - * Log messages sent to the context will be sent to the global log handler too.
 - *
 - * If libusb is compiled without message logging or USE_SYSTEM_LOGGING_FACILITY
 - * is defined then global callback function will never be called.
 - * If ENABLE_DEBUG_LOGGING is defined then per context callback function will
 - * never be called.
 - *
 - * \param ctx context on which to assign log handler, or NULL for the default
 - * context. Parameter ignored if only LIBUSB_LOG_CB_GLOBAL mode is requested.
 - * \param cb pointer to the callback function, or NULL to stop log
 - * messages redirection
 - * \param mode mode of callback function operation. Several modes can be
 - * selected for a single callback function, see \ref libusb_log_cb_mode for
 - * a description.
 - * \see libusb_log_cb, libusb_log_cb_mode
 - */
 -void API_EXPORTED libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb,
 -      int mode)
 -{
 -#if defined(ENABLE_LOGGING) && (!defined(ENABLE_DEBUG_LOGGING) || !defined(USE_SYSTEM_LOGGING_FACILITY))
 -#if !defined(USE_SYSTEM_LOGGING_FACILITY)
 -      if (mode & LIBUSB_LOG_CB_GLOBAL)
 -              log_handler = cb;
 -#endif
 -#if !defined(ENABLE_DEBUG_LOGGING)
 -      if (mode & LIBUSB_LOG_CB_CONTEXT) {
 -              ctx = usbi_get_context(ctx);
 -              ctx->log_handler = cb;
 -      }
 -#else
 -      UNUSED(ctx);
 -#endif
 -#else
 -      UNUSED(ctx);
 -      UNUSED(cb);
 -      UNUSED(mode);
--#endif
--}
--
--/** \ingroup libusb_lib
-- * Set an option in the library.
-- *
-- * Use this function to configure a specific option within the library.
-- *
-- * Some options require one or more arguments to be provided. Consult each
-- * option's documentation for specific requirements.
-- *
-- * Since version 1.0.22, \ref LIBUSB_API_VERSION >= 0x01000106
-- *
-- * \param ctx context on which to operate
-- * \param option which option to set
-- * \param ... any required arguments for the specified option
-- *
-- * \returns LIBUSB_SUCCESS on success
-- * \returns LIBUSB_ERROR_INVALID_PARAM if the option or arguments are invalid
-- * \returns LIBUSB_ERROR_NOT_SUPPORTED if the option is valid but not supported
-- * on this platform
 - * \returns LIBUSB_ERROR_NOT_FOUND if LIBUSB_OPTION_USE_USBDK is valid on this platform but UsbDk is not available
-- */
--int API_EXPORTED libusb_set_option(libusb_context *ctx,
--      enum libusb_option option, ...)
--{
--      int arg, r = LIBUSB_SUCCESS;
--      va_list ap;
--
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--
--      va_start(ap, option);
--      switch (option) {
--      case LIBUSB_OPTION_LOG_LEVEL:
--              arg = va_arg(ap, int);
--              if (arg < LIBUSB_LOG_LEVEL_NONE || arg > LIBUSB_LOG_LEVEL_DEBUG) {
--                      r = LIBUSB_ERROR_INVALID_PARAM;
--                      break;
--              }
--#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
--              if (!ctx->debug_fixed)
--                      ctx->debug = (enum libusb_log_level)arg;
--#endif
--              break;
--
--      /* Handle all backend-specific options here */
--      case LIBUSB_OPTION_USE_USBDK:
 -      case LIBUSB_OPTION_WEAK_AUTHORITY:
--              if (usbi_backend.set_option)
--                      r = usbi_backend.set_option(ctx, option, ap);
--              else
--                      r = LIBUSB_ERROR_NOT_SUPPORTED;
--              break;
--
--      default:
--              r = LIBUSB_ERROR_INVALID_PARAM;
--      }
--      va_end(ap);
--
--      return r;
--}
--
--#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
--/* returns the log level as defined in the LIBUSB_DEBUG environment variable.
-- * if LIBUSB_DEBUG is not present or not a number, returns LIBUSB_LOG_LEVEL_NONE.
-- * value is clamped to ensure it is within the valid range of possibilities.
-- */
--static enum libusb_log_level get_env_debug_level(void)
--{
--      const char *dbg = getenv("LIBUSB_DEBUG");
--      enum libusb_log_level level;
--      if (dbg) {
--              int dbg_level = atoi(dbg);
--              dbg_level = CLAMP(dbg_level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
--              level = (enum libusb_log_level)dbg_level;
--      } else {
--              level = LIBUSB_LOG_LEVEL_NONE;
--      }
--      return level;
--}
--#endif
--
--/** \ingroup libusb_lib
-- * Initialize libusb. This function must be called before calling any other
-- * libusb function.
-- *
-- * If you do not provide an output location for a context pointer, a default
-- * context will be created. If there was already a default context, it will
-- * be reused (and nothing will be initialized/reinitialized).
-- *
-- * \param context Optional output location for context pointer.
-- * Only valid on return code 0.
-- * \returns 0 on success, or a LIBUSB_ERROR code on failure
-- * \see libusb_contexts
-- */
--int API_EXPORTED libusb_init(libusb_context **context)
--{
--      struct libusb_device *dev, *next;
--      size_t priv_size = usbi_backend.context_priv_size;
--      struct libusb_context *ctx;
--      static int first_init = 1;
--      int r = 0;
--
--      usbi_mutex_static_lock(&default_context_lock);
--
-       if (!timestamp_origin.tv_sec) {
-               usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &timestamp_origin);
-       }
 -      if (!timestamp_origin.tv_sec)
 -              usbi_get_monotonic_time(&timestamp_origin);
--
--      if (!context && usbi_default_context) {
--              usbi_dbg("reusing default context");
--              default_context_refcnt++;
--              usbi_mutex_static_unlock(&default_context_lock);
--              return 0;
--      }
--
-       ctx = calloc(1, sizeof(*ctx) + priv_size);
 -      ctx = calloc(1, PTR_ALIGN(sizeof(*ctx)) + priv_size);
--      if (!ctx) {
--              r = LIBUSB_ERROR_NO_MEM;
--              goto err_unlock;
--      }
--
--#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
--      ctx->debug = get_env_debug_level();
--      if (ctx->debug != LIBUSB_LOG_LEVEL_NONE)
--              ctx->debug_fixed = 1;
--#endif
--
--      /* default context should be initialized before calling usbi_dbg */
--      if (!usbi_default_context) {
--              usbi_default_context = ctx;
--              default_context_refcnt++;
--              usbi_dbg("created default context");
--      }
--
--      usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
--              libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
--
--      usbi_mutex_init(&ctx->usb_devs_lock);
--      usbi_mutex_init(&ctx->open_devs_lock);
--      usbi_mutex_init(&ctx->hotplug_cbs_lock);
--      list_init(&ctx->usb_devs);
--      list_init(&ctx->open_devs);
--      list_init(&ctx->hotplug_cbs);
--      ctx->next_hotplug_cb_handle = 1;
--
--      usbi_mutex_static_lock(&active_contexts_lock);
--      if (first_init) {
--              first_init = 0;
-               list_init (&active_contexts_list);
 -              list_init(&active_contexts_list);
--      }
--      list_add (&ctx->list, &active_contexts_list);
--      usbi_mutex_static_unlock(&active_contexts_lock);
--
--      if (usbi_backend.init) {
--              r = usbi_backend.init(ctx);
--              if (r)
--                      goto err_free_ctx;
--      }
--
--      r = usbi_io_init(ctx);
--      if (r < 0)
--              goto err_backend_exit;
--
--      usbi_mutex_static_unlock(&default_context_lock);
--
--      if (context)
--              *context = ctx;
--
--      return 0;
--
--err_backend_exit:
--      if (usbi_backend.exit)
--              usbi_backend.exit(ctx);
--err_free_ctx:
--      if (ctx == usbi_default_context) {
--              usbi_default_context = NULL;
--              default_context_refcnt--;
--      }
--
--      usbi_mutex_static_lock(&active_contexts_lock);
-       list_del (&ctx->list);
 -      list_del(&ctx->list);
--      usbi_mutex_static_unlock(&active_contexts_lock);
--
--      usbi_mutex_lock(&ctx->usb_devs_lock);
-       list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
 -      for_each_device_safe(ctx, dev, next) {
--              list_del(&dev->list);
--              libusb_unref_device(dev);
--      }
--      usbi_mutex_unlock(&ctx->usb_devs_lock);
--
--      usbi_mutex_destroy(&ctx->open_devs_lock);
--      usbi_mutex_destroy(&ctx->usb_devs_lock);
--      usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
--
--      free(ctx);
--err_unlock:
--      usbi_mutex_static_unlock(&default_context_lock);
--      return r;
--}
--
--/** \ingroup libusb_lib
-- * Deinitialize libusb. Should be called after closing all open devices and
-- * before your application terminates.
-- * \param ctx the context to deinitialize, or NULL for the default context
-- */
- void API_EXPORTED libusb_exit(struct libusb_context *ctx)
 -void API_EXPORTED libusb_exit(libusb_context *ctx)
--{
--      struct libusb_device *dev, *next;
--      struct timeval tv = { 0, 0 };
 -      int destroying_default_context = 0;
--
-       usbi_dbg("");
-       USBI_GET_CONTEXT(ctx);
 -      usbi_dbg(" ");
 -
 -      ctx = usbi_get_context(ctx);
--
--      /* if working with default context, only actually do the deinitialization
--       * if we're the last user */
--      usbi_mutex_static_lock(&default_context_lock);
--      if (ctx == usbi_default_context) {
 -              if (!usbi_default_context) {
 -                      usbi_dbg("no default context, not initialized?");
 -                      usbi_mutex_static_unlock(&default_context_lock);
 -                      return;
 -              }
 -
--              if (--default_context_refcnt > 0) {
--                      usbi_dbg("not destroying default context");
--                      usbi_mutex_static_unlock(&default_context_lock);
--                      return;
--              }
--              usbi_dbg("destroying default context");
-               usbi_default_context = NULL;
 -
 -              /*
 -               * Setting this flag without unlocking the default context, as
 -               * we are actually destroying the default context.
 -               * usbi_default_context is not set to NULL yet, as all activities
 -               * would only stop after usbi_backend->exit() returns.
 -               */
 -              destroying_default_context = 1;
 -      } else {
 -              /* Unlock default context, as we're not modifying it. */
 -              usbi_mutex_static_unlock(&default_context_lock);
--      }
-       usbi_mutex_static_unlock(&default_context_lock);
--
--      usbi_mutex_static_lock(&active_contexts_lock);
-       list_del (&ctx->list);
 -      list_del(&ctx->list);
--      usbi_mutex_static_unlock(&active_contexts_lock);
--
--      if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
--              usbi_hotplug_deregister(ctx, 1);
--
--              /*
--               * Ensure any pending unplug events are read from the hotplug
--               * pipe. The usb_device-s hold in the events are no longer part
--               * of usb_devs, but the events still hold a reference!
--               *
--               * Note we don't do this if the application has left devices
--               * open (which implies a buggy app) to avoid packet completion
--               * handlers running when the app does not expect them to run.
--               */
--              if (list_empty(&ctx->open_devs))
--                      libusb_handle_events_timeout(ctx, &tv);
--
--              usbi_mutex_lock(&ctx->usb_devs_lock);
-               list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
 -              for_each_device_safe(ctx, dev, next) {
--                      list_del(&dev->list);
--                      libusb_unref_device(dev);
--              }
--              usbi_mutex_unlock(&ctx->usb_devs_lock);
--      }
--
--      /* a few sanity checks. don't bother with locking because unless
--       * there is an application bug, nobody will be accessing these. */
--      if (!list_empty(&ctx->usb_devs))
--              usbi_warn(ctx, "some libusb_devices were leaked");
--      if (!list_empty(&ctx->open_devs))
--              usbi_warn(ctx, "application left some devices open");
--
--      usbi_io_exit(ctx);
--      if (usbi_backend.exit)
--              usbi_backend.exit(ctx);
--
--      usbi_mutex_destroy(&ctx->open_devs_lock);
--      usbi_mutex_destroy(&ctx->usb_devs_lock);
--      usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
--      free(ctx);
 -
 -      if (destroying_default_context) {
 -              usbi_default_context = NULL;
 -              usbi_mutex_static_unlock(&default_context_lock);
 -      }
--}
--
--/** \ingroup libusb_misc
-- * Check at runtime if the loaded library has a given capability.
-- * This call should be performed after \ref libusb_init(), to ensure the
-- * backend has updated its capability set.
-- *
-- * \param capability the \ref libusb_capability to check for
-- * \returns nonzero if the running library has the capability, 0 otherwise
-- */
--int API_EXPORTED libusb_has_capability(uint32_t capability)
--{
--      switch (capability) {
--      case LIBUSB_CAP_HAS_CAPABILITY:
--              return 1;
--      case LIBUSB_CAP_HAS_HOTPLUG:
--              return !(usbi_backend.get_device_list);
--      case LIBUSB_CAP_HAS_HID_ACCESS:
--              return (usbi_backend.caps & USBI_CAP_HAS_HID_ACCESS);
--      case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
--              return (usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
--      }
--      return 0;
--}
--
--#ifdef ENABLE_LOGGING
--
--/* this is defined in libusbi.h if needed */
--#ifdef LIBUSB_PRINTF_WIN32
--/*
-- * Prior to VS2015, Microsoft did not provide the snprintf() function and
-  * provided a vsnprintf() that did not guarantee NULL-terminated output.
 - * provided a vsnprintf() that did not guarantee NUL-terminated output.
-- * Microsoft did provide a _snprintf() function, but again it did not
-- * guarantee NULL-terminated output.
-- *
-  * The below implementations guarantee NULL-terminated output and are
 - * The below implementations guarantee NUL-terminated output and are
-- * C99 compliant.
-- */
--
--int usbi_snprintf(char *str, size_t size, const char *format, ...)
--{
-       va_list ap;
 -      va_list args;
--      int ret;
--
-       va_start(ap, format);
-       ret = usbi_vsnprintf(str, size, format, ap);
-       va_end(ap);
 -      va_start(args, format);
 -      ret = usbi_vsnprintf(str, size, format, args);
 -      va_end(args);
--
--      return ret;
--}
--
- int usbi_vsnprintf(char *str, size_t size, const char *format, va_list ap)
 -int usbi_vsnprintf(char *str, size_t size, const char *format, va_list args)
--{
--      int ret;
--
-       ret = _vsnprintf(str, size, format, ap);
 -      ret = _vsnprintf(str, size, format, args);
--      if (ret < 0 || ret == (int)size) {
-               /* Output is truncated, ensure buffer is NULL-terminated and
 -              /* Output is truncated, ensure buffer is NUL-terminated and
--               * determine how many characters would have been written. */
--              str[size - 1] = '\0';
--              if (ret < 0)
-                       ret = _vsnprintf(NULL, 0, format, ap);
 -                      ret = _vsnprintf(NULL, 0, format, args);
--      }
--
--      return ret;
--}
--#endif /* LIBUSB_PRINTF_WIN32 */
--
- static void usbi_log_str(enum libusb_log_level level, const char *str)
 -static void log_str(enum libusb_log_level level, const char *str)
--{
--#if defined(USE_SYSTEM_LOGGING_FACILITY)
- #if defined(OS_WINDOWS)
-       OutputDebugString(str);
- #elif defined(OS_WINCE)
-       /* Windows CE only supports the Unicode version of OutputDebugString. */
-       WCHAR wbuf[USBI_MAX_LOG_LEN];
-       MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
-       OutputDebugStringW(wbuf);
- #elif defined(__ANDROID__)
-       int priority = ANDROID_LOG_UNKNOWN;
 -#if defined(__ANDROID__)
 -      int priority;
--      switch (level) {
-       case LIBUSB_LOG_LEVEL_NONE: return;
 -      case LIBUSB_LOG_LEVEL_NONE: return;     /* Impossible, but keeps compiler happy */
--      case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
--      case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
--      case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
--      case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
 -      default: priority = ANDROID_LOG_UNKNOWN;
--      }
--      __android_log_write(priority, "libusb", str);
- #elif defined(HAVE_SYSLOG_FUNC)
-       int syslog_level = LOG_INFO;
 -#elif defined(_WIN32)
 -      UNUSED(level);
 -      OutputDebugStringA(str);
 -#elif defined(HAVE_SYSLOG)
 -      int syslog_level;
--      switch (level) {
-       case LIBUSB_LOG_LEVEL_NONE: return;
 -      case LIBUSB_LOG_LEVEL_NONE: return;     /* Impossible, but keeps compiler happy */
--      case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
--      case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
--      case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
--      case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
 -      default: syslog_level = LOG_INFO;
--      }
--      syslog(syslog_level, "%s", str);
- #else /* All of gcc, Clang, XCode seem to use #warning */
 -#else /* All of gcc, Clang, Xcode seem to use #warning */
--#warning System logging is not supported on this platform. Logging to stderr will be used instead.
 -      UNUSED(level);
--      fputs(str, stderr);
--#endif
--#else
-       fputs(str, stderr);
 -      /* Global log handler */
 -      if (log_handler)
 -              log_handler(NULL, level, str);
 -      else
 -              fputs(str, stderr);
--#endif /* USE_SYSTEM_LOGGING_FACILITY */
-       UNUSED(level);
--}
--
- void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
 -static void log_v(struct libusb_context *ctx, enum libusb_log_level level,
--      const char *function, const char *format, va_list args)
--{
--      const char *prefix;
--      char buf[USBI_MAX_LOG_LEN];
-       struct timespec now;
--      int global_debug, header_len, text_len;
--      static int has_debug_header_been_displayed = 0;
--
--#ifdef ENABLE_DEBUG_LOGGING
--      global_debug = 1;
--      UNUSED(ctx);
--#else
-       enum libusb_log_level ctx_level = LIBUSB_LOG_LEVEL_NONE;
 -      enum libusb_log_level ctx_level;
--
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      if (ctx)
--              ctx_level = ctx->debug;
--      else
--              ctx_level = get_env_debug_level();
--
-       if (ctx_level == LIBUSB_LOG_LEVEL_NONE)
-               return;
-       if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
-               return;
-       if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
-               return;
-       if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
 -      if (ctx_level < level)
--              return;
--
--      global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
--#endif
-       usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &now);
-       if ((global_debug) && (!has_debug_header_been_displayed)) {
-               has_debug_header_been_displayed = 1;
-               usbi_log_str(LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
-               usbi_log_str(LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
-       }
-       if (now.tv_nsec < timestamp_origin.tv_nsec) {
-               now.tv_sec--;
-               now.tv_nsec += 1000000000L;
-       }
-       now.tv_sec -= timestamp_origin.tv_sec;
-       now.tv_nsec -= timestamp_origin.tv_nsec;
--
--      switch (level) {
-       case LIBUSB_LOG_LEVEL_NONE:
 -      case LIBUSB_LOG_LEVEL_NONE:     /* Impossible, but keeps compiler happy */
--              return;
--      case LIBUSB_LOG_LEVEL_ERROR:
--              prefix = "error";
--              break;
--      case LIBUSB_LOG_LEVEL_WARNING:
--              prefix = "warning";
--              break;
--      case LIBUSB_LOG_LEVEL_INFO:
--              prefix = "info";
--              break;
--      case LIBUSB_LOG_LEVEL_DEBUG:
--              prefix = "debug";
--              break;
--      default:
--              prefix = "unknown";
--              break;
--      }
--
--      if (global_debug) {
 -              struct timespec timestamp;
 -
 -              if (!has_debug_header_been_displayed) {
 -                      has_debug_header_been_displayed = 1;
 -                      log_str(LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
 -                      log_str(LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
 -              }
 -
 -              usbi_get_monotonic_time(&timestamp);
 -              TIMESPEC_SUB(&timestamp, &timestamp_origin, &timestamp);
 -
--              header_len = snprintf(buf, sizeof(buf),
-                       "[%2d.%06d] [%08x] libusb: %s [%s] ",
-                       (int)now.tv_sec, (int)(now.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
 -                      "[%2ld.%06ld] [%08x] libusb: %s [%s] ",
 -                      (long)timestamp.tv_sec, (long)(timestamp.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
--      } else {
--              header_len = snprintf(buf, sizeof(buf),
--                      "libusb: %s [%s] ", prefix, function);
--      }
--
--      if (header_len < 0 || header_len >= (int)sizeof(buf)) {
-               /* Somehow snprintf failed to write to the buffer,
 -              /* Somehow snprintf() failed to write to the buffer,
--               * remove the header so something useful is output. */
--              header_len = 0;
--      }
-       /* Make sure buffer is NUL terminated */
-       buf[header_len] = '\0';
-       text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
 -
 -      text_len = vsnprintf(buf + header_len, sizeof(buf) - (size_t)header_len,
--              format, args);
--      if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
--              /* Truncated log output. On some platforms a -1 return value means
--               * that the output was truncated. */
-               text_len = sizeof(buf) - header_len;
 -              text_len = (int)sizeof(buf) - header_len;
--      }
-       if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
 -      if (header_len + text_len + (int)sizeof(USBI_LOG_LINE_END) >= (int)sizeof(buf)) {
--              /* Need to truncate the text slightly to fit on the terminator. */
-               text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
 -              text_len -= (header_len + text_len + (int)sizeof(USBI_LOG_LINE_END)) - (int)sizeof(buf);
--      }
--      strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
--
-       usbi_log_str(level, buf);
 -      log_str(level, buf);
 -
 -      /* Per-context log handler */
 -#ifndef ENABLE_DEBUG_LOGGING
 -      if (ctx && ctx->log_handler)
 -              ctx->log_handler(ctx, level, buf);
 -#endif
--}
--
--void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
--      const char *function, const char *format, ...)
--{
--      va_list args;
--
-       va_start (args, format);
-       usbi_log_v(ctx, level, function, format, args);
-       va_end (args);
 -      va_start(args, format);
 -      log_v(ctx, level, function, format, args);
 -      va_end(args);
--}
--
--#endif /* ENABLE_LOGGING */
--
--/** \ingroup libusb_misc
-- * Returns a constant NULL-terminated string with the ASCII name of a libusb
-- * error or transfer status code. The caller must not free() the returned
-- * string.
-- *
-- * \param error_code The \ref libusb_error or libusb_transfer_status code to
-- * return the name of.
-- * \returns The error name, or the string **UNKNOWN** if the value of
-- * error_code is not a known error / status code.
-- */
--DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
--{
--      switch (error_code) {
--      case LIBUSB_ERROR_IO:
--              return "LIBUSB_ERROR_IO";
--      case LIBUSB_ERROR_INVALID_PARAM:
--              return "LIBUSB_ERROR_INVALID_PARAM";
--      case LIBUSB_ERROR_ACCESS:
--              return "LIBUSB_ERROR_ACCESS";
--      case LIBUSB_ERROR_NO_DEVICE:
--              return "LIBUSB_ERROR_NO_DEVICE";
--      case LIBUSB_ERROR_NOT_FOUND:
--              return "LIBUSB_ERROR_NOT_FOUND";
--      case LIBUSB_ERROR_BUSY:
--              return "LIBUSB_ERROR_BUSY";
--      case LIBUSB_ERROR_TIMEOUT:
--              return "LIBUSB_ERROR_TIMEOUT";
--      case LIBUSB_ERROR_OVERFLOW:
--              return "LIBUSB_ERROR_OVERFLOW";
--      case LIBUSB_ERROR_PIPE:
--              return "LIBUSB_ERROR_PIPE";
--      case LIBUSB_ERROR_INTERRUPTED:
--              return "LIBUSB_ERROR_INTERRUPTED";
--      case LIBUSB_ERROR_NO_MEM:
--              return "LIBUSB_ERROR_NO_MEM";
--      case LIBUSB_ERROR_NOT_SUPPORTED:
--              return "LIBUSB_ERROR_NOT_SUPPORTED";
--      case LIBUSB_ERROR_OTHER:
--              return "LIBUSB_ERROR_OTHER";
--
--      case LIBUSB_TRANSFER_ERROR:
--              return "LIBUSB_TRANSFER_ERROR";
--      case LIBUSB_TRANSFER_TIMED_OUT:
--              return "LIBUSB_TRANSFER_TIMED_OUT";
--      case LIBUSB_TRANSFER_CANCELLED:
--              return "LIBUSB_TRANSFER_CANCELLED";
--      case LIBUSB_TRANSFER_STALL:
--              return "LIBUSB_TRANSFER_STALL";
--      case LIBUSB_TRANSFER_NO_DEVICE:
--              return "LIBUSB_TRANSFER_NO_DEVICE";
--      case LIBUSB_TRANSFER_OVERFLOW:
--              return "LIBUSB_TRANSFER_OVERFLOW";
--
--      case 0:
--              return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
--      default:
--              return "**UNKNOWN**";
--      }
--}
--
--/** \ingroup libusb_misc
-- * Returns a pointer to const struct libusb_version with the version
-- * (major, minor, micro, nano and rc) of the running library.
-- */
--DEFAULT_VISIBILITY
--const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
--{
--      return &libusb_version_internal;
--}
diff --cc mac/libusb/descriptor.c
index 74d6de557eabdb2f6bbd97702cf27fff7834da8c,ecd9441804e6b3692dc25933f618592429e7384e..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1192 -1,1139 +1,0 @@@
--/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
--/*
-- * USB descriptor handling functions for libusb
-- * Copyright © 2007 Daniel Drake <dsd@gentoo.org>
-- * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
- #include <config.h>
 -#include "libusbi.h"
--
- #include <errno.h>
- #include <stdint.h>
- #include <stdlib.h>
--#include <string.h>
- #include "libusbi.h"
--
- #define DESC_HEADER_LENGTH            2
- #define DEVICE_DESC_LENGTH            18
- #define CONFIG_DESC_LENGTH            9
- #define INTERFACE_DESC_LENGTH         9
- #define ENDPOINT_DESC_LENGTH          7
- #define ENDPOINT_AUDIO_DESC_LENGTH    9
 -#define DESC_HEADER_LENGTH    2
--
--/** @defgroup libusb_desc USB descriptors
-- * This page details how to examine the various standard USB descriptors
-- * for detected devices
-- */
--
- /* set host_endian if the w values are already in host endian format,
-  * as opposed to bus endian. */
- int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
-       void *dest, int host_endian)
 -#define READ_LE16(p) ((uint16_t)      \
 -      (((uint16_t)((p)[1]) << 8) |    \
 -       ((uint16_t)((p)[0]))))
 -
 -#define READ_LE32(p) ((uint32_t)      \
 -      (((uint32_t)((p)[3]) << 24) |   \
 -       ((uint32_t)((p)[2]) << 16) |   \
 -       ((uint32_t)((p)[1]) <<  8) |   \
 -       ((uint32_t)((p)[0]))))
 -
 -static void parse_descriptor(const void *source, const char *descriptor, void *dest)
--{
-       const unsigned char *sp = source;
-       unsigned char *dp = dest;
-       uint16_t w;
-       const char *cp;
-       uint32_t d;
 -      const uint8_t *sp = source;
 -      uint8_t *dp = dest;
 -      char field_type;
--
-       for (cp = descriptor; *cp; cp++) {
-               switch (*cp) {
-                       case 'b':       /* 8-bit byte */
-                               *dp++ = *sp++;
-                               break;
-                       case 'w':       /* 16-bit word, convert from little endian to CPU */
-                               dp += ((uintptr_t)dp & 1);      /* Align to word boundary */
 -      while (*descriptor) {
 -              field_type = *descriptor++;
 -              switch (field_type) {
 -              case 'b':       /* 8-bit byte */
 -                      *dp++ = *sp++;
 -                      break;
 -              case 'w':       /* 16-bit word, convert from little endian to CPU */
 -                      dp += ((uintptr_t)dp & 1);      /* Align to 16-bit word boundary */
--
-                               if (host_endian) {
-                                       memcpy(dp, sp, 2);
-                               } else {
-                                       w = (sp[1] << 8) | sp[0];
-                                       *((uint16_t *)dp) = w;
-                               }
-                               sp += 2;
-                               dp += 2;
-                               break;
-                       case 'd':       /* 32-bit word, convert from little endian to CPU */
-                               dp += ((uintptr_t)dp & 1);      /* Align to word boundary */
 -                      *((uint16_t *)dp) = READ_LE16(sp);
 -                      sp += 2;
 -                      dp += 2;
 -                      break;
 -              case 'd':       /* 32-bit word, convert from little endian to CPU */
 -                      dp += 4 - ((uintptr_t)dp & 3);  /* Align to 32-bit word boundary */
--
-                               if (host_endian) {
-                                       memcpy(dp, sp, 4);
-                               } else {
-                                       d = (sp[3] << 24) | (sp[2] << 16) |
-                                               (sp[1] << 8) | sp[0];
-                                       *((uint32_t *)dp) = d;
-                               }
-                               sp += 4;
-                               dp += 4;
-                               break;
-                       case 'u':       /* 16 byte UUID */
-                               memcpy(dp, sp, 16);
-                               sp += 16;
-                               dp += 16;
-                               break;
 -                      *((uint32_t *)dp) = READ_LE32(sp);
 -                      sp += 4;
 -                      dp += 4;
 -                      break;
 -              case 'u':       /* 16 byte UUID */
 -                      memcpy(dp, sp, 16);
 -                      sp += 16;
 -                      dp += 16;
 -                      break;
--              }
--      }
-       return (int) (sp - source);
--}
--
--static void clear_endpoint(struct libusb_endpoint_descriptor *endpoint)
--{
-       free((void *) endpoint->extra);
 -      free((void *)endpoint->extra);
--}
--
--static int parse_endpoint(struct libusb_context *ctx,
-       struct libusb_endpoint_descriptor *endpoint, unsigned char *buffer,
-       int size, int host_endian)
 -      struct libusb_endpoint_descriptor *endpoint, const uint8_t *buffer, int size)
--{
-       struct usb_descriptor_header header;
-       unsigned char *extra;
-       unsigned char *begin;
 -      const struct usbi_descriptor_header *header;
 -      const uint8_t *begin;
 -      void *extra;
--      int parsed = 0;
--      int len;
--
--      if (size < DESC_HEADER_LENGTH) {
--              usbi_err(ctx, "short endpoint descriptor read %d/%d",
--                       size, DESC_HEADER_LENGTH);
--              return LIBUSB_ERROR_IO;
--      }
--
-       usbi_parse_descriptor(buffer, "bb", &header, 0);
-       if (header.bDescriptorType != LIBUSB_DT_ENDPOINT) {
-               usbi_err(ctx, "unexpected descriptor %x (expected %x)",
-                       header.bDescriptorType, LIBUSB_DT_ENDPOINT);
-               return parsed;
-       }
-       if (header.bLength > size) {
-               usbi_warn(ctx, "short endpoint descriptor read %d/%d",
-                         size, header.bLength);
 -      header = (const struct usbi_descriptor_header *)buffer;
 -      if (header->bDescriptorType != LIBUSB_DT_ENDPOINT) {
 -              usbi_err(ctx, "unexpected descriptor 0x%x (expected 0x%x)",
 -                      header->bDescriptorType, LIBUSB_DT_ENDPOINT);
--              return parsed;
-       }
-       if (header.bLength >= ENDPOINT_AUDIO_DESC_LENGTH)
-               usbi_parse_descriptor(buffer, "bbbbwbbb", endpoint, host_endian);
-       else if (header.bLength >= ENDPOINT_DESC_LENGTH)
-               usbi_parse_descriptor(buffer, "bbbbwb", endpoint, host_endian);
-       else {
-               usbi_err(ctx, "invalid endpoint bLength (%d)", header.bLength);
 -      } else if (header->bLength < LIBUSB_DT_ENDPOINT_SIZE) {
 -              usbi_err(ctx, "invalid endpoint bLength (%u)", header->bLength);
--              return LIBUSB_ERROR_IO;
 -      } else if (header->bLength > size) {
 -              usbi_warn(ctx, "short endpoint descriptor read %d/%u",
 -                        size, header->bLength);
 -              return parsed;
--      }
--
-       buffer += header.bLength;
-       size -= header.bLength;
-       parsed += header.bLength;
 -      if (header->bLength >= LIBUSB_DT_ENDPOINT_AUDIO_SIZE)
 -              parse_descriptor(buffer, "bbbbwbbb", endpoint);
 -      else
 -              parse_descriptor(buffer, "bbbbwb", endpoint);
 -
 -      buffer += header->bLength;
 -      size -= header->bLength;
 -      parsed += header->bLength;
--
--      /* Skip over the rest of the Class Specific or Vendor Specific */
--      /*  descriptors */
--      begin = buffer;
--      while (size >= DESC_HEADER_LENGTH) {
-               usbi_parse_descriptor(buffer, "bb", &header, 0);
-               if (header.bLength < DESC_HEADER_LENGTH) {
-                       usbi_err(ctx, "invalid extra ep desc len (%d)",
-                                header.bLength);
 -              header = (const struct usbi_descriptor_header *)buffer;
 -              if (header->bLength < DESC_HEADER_LENGTH) {
 -                      usbi_err(ctx, "invalid extra ep desc len (%u)",
 -                               header->bLength);
--                      return LIBUSB_ERROR_IO;
-               } else if (header.bLength > size) {
-                       usbi_warn(ctx, "short extra ep desc read %d/%d",
-                                 size, header.bLength);
 -              } else if (header->bLength > size) {
 -                      usbi_warn(ctx, "short extra ep desc read %d/%u",
 -                                size, header->bLength);
--                      return parsed;
--              }
--
--              /* If we find another "proper" descriptor then we're done  */
-               if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
-                               (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
-                               (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
-                               (header.bDescriptorType == LIBUSB_DT_DEVICE))
 -              if (header->bDescriptorType == LIBUSB_DT_ENDPOINT ||
 -                  header->bDescriptorType == LIBUSB_DT_INTERFACE ||
 -                  header->bDescriptorType == LIBUSB_DT_CONFIG ||
 -                  header->bDescriptorType == LIBUSB_DT_DEVICE)
--                      break;
--
-               usbi_dbg("skipping descriptor %x", header.bDescriptorType);
-               buffer += header.bLength;
-               size -= header.bLength;
-               parsed += header.bLength;
 -              usbi_dbg("skipping descriptor 0x%x", header->bDescriptorType);
 -              buffer += header->bLength;
 -              size -= header->bLength;
 -              parsed += header->bLength;
--      }
--
--      /* Copy any unknown descriptors into a storage area for drivers */
--      /*  to later parse */
--      len = (int)(buffer - begin);
-       if (!len) {
-               endpoint->extra = NULL;
-               endpoint->extra_length = 0;
 -      if (len <= 0)
--              return parsed;
-       }
--
-       extra = malloc(len);
-       endpoint->extra = extra;
-       if (!extra) {
-               endpoint->extra_length = 0;
 -      extra = malloc((size_t)len);
 -      if (!extra)
--              return LIBUSB_ERROR_NO_MEM;
-       }
--
--      memcpy(extra, begin, len);
 -      endpoint->extra = extra;
--      endpoint->extra_length = len;
--
--      return parsed;
--}
--
--static void clear_interface(struct libusb_interface *usb_interface)
--{
--      int i;
-       int j;
--
--      if (usb_interface->altsetting) {
--              for (i = 0; i < usb_interface->num_altsetting; i++) {
--                      struct libusb_interface_descriptor *ifp =
--                              (struct libusb_interface_descriptor *)
--                              usb_interface->altsetting + i;
-                       free((void *) ifp->extra);
 -
 -                      free((void *)ifp->extra);
--                      if (ifp->endpoint) {
 -                              uint8_t j;
 -
--                              for (j = 0; j < ifp->bNumEndpoints; j++)
--                                      clear_endpoint((struct libusb_endpoint_descriptor *)
--                                                     ifp->endpoint + j);
--                      }
-                       free((void *) ifp->endpoint);
 -                      free((void *)ifp->endpoint);
--              }
--      }
-       free((void *) usb_interface->altsetting);
 -      free((void *)usb_interface->altsetting);
--      usb_interface->altsetting = NULL;
--}
--
--static int parse_interface(libusb_context *ctx,
-       struct libusb_interface *usb_interface, unsigned char *buffer, int size,
-       int host_endian)
 -      struct libusb_interface *usb_interface, const uint8_t *buffer, int size)
--{
-       int i;
--      int len;
--      int r;
--      int parsed = 0;
--      int interface_number = -1;
-       struct usb_descriptor_header header;
 -      const struct usbi_descriptor_header *header;
 -      const struct usbi_interface_descriptor *if_desc;
--      struct libusb_interface_descriptor *ifp;
-       unsigned char *begin;
 -      const uint8_t *begin;
--
-       usb_interface->num_altsetting = 0;
 -      while (size >= LIBUSB_DT_INTERFACE_SIZE) {
 -              struct libusb_interface_descriptor *altsetting;
--
-       while (size >= INTERFACE_DESC_LENGTH) {
-               struct libusb_interface_descriptor *altsetting =
-                       (struct libusb_interface_descriptor *) usb_interface->altsetting;
-               altsetting = usbi_reallocf(altsetting,
-                       sizeof(struct libusb_interface_descriptor) *
-                       (usb_interface->num_altsetting + 1));
 -              altsetting = realloc((void *)usb_interface->altsetting,
 -                      sizeof(*altsetting) * (size_t)(usb_interface->num_altsetting + 1));
--              if (!altsetting) {
--                      r = LIBUSB_ERROR_NO_MEM;
--                      goto err;
--              }
--              usb_interface->altsetting = altsetting;
--
--              ifp = altsetting + usb_interface->num_altsetting;
-               usbi_parse_descriptor(buffer, "bbbbbbbbb", ifp, 0);
 -              parse_descriptor(buffer, "bbbbbbbbb", ifp);
--              if (ifp->bDescriptorType != LIBUSB_DT_INTERFACE) {
-                       usbi_err(ctx, "unexpected descriptor %x (expected %x)",
 -                      usbi_err(ctx, "unexpected descriptor 0x%x (expected 0x%x)",
--                               ifp->bDescriptorType, LIBUSB_DT_INTERFACE);
--                      return parsed;
-               }
-               if (ifp->bLength < INTERFACE_DESC_LENGTH) {
-                       usbi_err(ctx, "invalid interface bLength (%d)",
 -              } else if (ifp->bLength < LIBUSB_DT_INTERFACE_SIZE) {
 -                      usbi_err(ctx, "invalid interface bLength (%u)",
--                               ifp->bLength);
--                      r = LIBUSB_ERROR_IO;
--                      goto err;
-               }
-               if (ifp->bLength > size) {
-                       usbi_warn(ctx, "short intf descriptor read %d/%d",
 -              } else if (ifp->bLength > size) {
 -                      usbi_warn(ctx, "short intf descriptor read %d/%u",
--                               size, ifp->bLength);
--                      return parsed;
-               }
-               if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
-                       usbi_err(ctx, "too many endpoints (%d)", ifp->bNumEndpoints);
 -              } else if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
 -                      usbi_err(ctx, "too many endpoints (%u)", ifp->bNumEndpoints);
--                      r = LIBUSB_ERROR_IO;
--                      goto err;
--              }
--
--              usb_interface->num_altsetting++;
--              ifp->extra = NULL;
--              ifp->extra_length = 0;
--              ifp->endpoint = NULL;
--
--              if (interface_number == -1)
--                      interface_number = ifp->bInterfaceNumber;
--
--              /* Skip over the interface */
--              buffer += ifp->bLength;
--              parsed += ifp->bLength;
--              size -= ifp->bLength;
--
--              begin = buffer;
--
--              /* Skip over any interface, class or vendor descriptors */
--              while (size >= DESC_HEADER_LENGTH) {
-                       usbi_parse_descriptor(buffer, "bb", &header, 0);
-                       if (header.bLength < DESC_HEADER_LENGTH) {
 -                      header = (const struct usbi_descriptor_header *)buffer;
 -                      if (header->bLength < DESC_HEADER_LENGTH) {
--                              usbi_err(ctx,
-                                        "invalid extra intf desc len (%d)",
-                                        header.bLength);
 -                                       "invalid extra intf desc len (%u)",
 -                                       header->bLength);
--                              r = LIBUSB_ERROR_IO;
--                              goto err;
-                       } else if (header.bLength > size) {
 -                      } else if (header->bLength > size) {
--                              usbi_warn(ctx,
-                                         "short extra intf desc read %d/%d",
-                                         size, header.bLength);
 -                                        "short extra intf desc read %d/%u",
 -                                        size, header->bLength);
--                              return parsed;
--                      }
--
--                      /* If we find another "proper" descriptor then we're done */
-                       if ((header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
-                                       (header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
-                                       (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
-                                       (header.bDescriptorType == LIBUSB_DT_DEVICE))
 -                      if (header->bDescriptorType == LIBUSB_DT_INTERFACE ||
 -                          header->bDescriptorType == LIBUSB_DT_ENDPOINT ||
 -                          header->bDescriptorType == LIBUSB_DT_CONFIG ||
 -                          header->bDescriptorType == LIBUSB_DT_DEVICE)
--                              break;
--
-                       buffer += header.bLength;
-                       parsed += header.bLength;
-                       size -= header.bLength;
 -                      buffer += header->bLength;
 -                      parsed += header->bLength;
 -                      size -= header->bLength;
--              }
--
--              /* Copy any unknown descriptors into a storage area for */
--              /*  drivers to later parse */
--              len = (int)(buffer - begin);
-               if (len) {
-                       ifp->extra = malloc(len);
-                       if (!ifp->extra) {
 -              if (len > 0) {
 -                      void *extra = malloc((size_t)len);
 -
 -                      if (!extra) {
--                              r = LIBUSB_ERROR_NO_MEM;
--                              goto err;
--                      }
-                       memcpy((unsigned char *) ifp->extra, begin, len);
 -
 -                      memcpy(extra, begin, len);
 -                      ifp->extra = extra;
--                      ifp->extra_length = len;
--              }
--
--              if (ifp->bNumEndpoints > 0) {
--                      struct libusb_endpoint_descriptor *endpoint;
-                       endpoint = calloc(ifp->bNumEndpoints, sizeof(struct libusb_endpoint_descriptor));
-                       ifp->endpoint = endpoint;
 -                      uint8_t i;
 -
 -                      endpoint = calloc(ifp->bNumEndpoints, sizeof(*endpoint));
--                      if (!endpoint) {
--                              r = LIBUSB_ERROR_NO_MEM;
--                              goto err;
--                      }
--
 -                      ifp->endpoint = endpoint;
--                      for (i = 0; i < ifp->bNumEndpoints; i++) {
-                               r = parse_endpoint(ctx, endpoint + i, buffer, size,
-                                       host_endian);
 -                              r = parse_endpoint(ctx, endpoint + i, buffer, size);
--                              if (r < 0)
--                                      goto err;
--                              if (r == 0) {
-                                       ifp->bNumEndpoints = (uint8_t)i;
 -                                      ifp->bNumEndpoints = i;
--                                      break;
--                              }
--
--                              buffer += r;
--                              parsed += r;
--                              size -= r;
--                      }
--              }
--
--              /* We check to see if it's an alternate to this one */
-               ifp = (struct libusb_interface_descriptor *) buffer;
 -              if_desc = (const struct usbi_interface_descriptor *)buffer;
--              if (size < LIBUSB_DT_INTERFACE_SIZE ||
-                               ifp->bDescriptorType != LIBUSB_DT_INTERFACE ||
-                               ifp->bInterfaceNumber != interface_number)
 -                  if_desc->bDescriptorType != LIBUSB_DT_INTERFACE ||
 -                  if_desc->bInterfaceNumber != interface_number)
--                      return parsed;
--      }
--
--      return parsed;
--err:
--      clear_interface(usb_interface);
--      return r;
--}
--
--static void clear_configuration(struct libusb_config_descriptor *config)
--{
-       int i;
 -      uint8_t i;
 -
--      if (config->interface) {
--              for (i = 0; i < config->bNumInterfaces; i++)
--                      clear_interface((struct libusb_interface *)
--                                      config->interface + i);
--      }
-       free((void *) config->interface);
-       free((void *) config->extra);
 -      free((void *)config->interface);
 -      free((void *)config->extra);
--}
--
--static int parse_configuration(struct libusb_context *ctx,
-       struct libusb_config_descriptor *config, unsigned char *buffer,
-       int size, int host_endian)
 -      struct libusb_config_descriptor *config, const uint8_t *buffer, int size)
--{
-       int i;
 -      uint8_t i;
--      int r;
-       struct usb_descriptor_header header;
 -      const struct usbi_descriptor_header *header;
--      struct libusb_interface *usb_interface;
--
--      if (size < LIBUSB_DT_CONFIG_SIZE) {
--              usbi_err(ctx, "short config descriptor read %d/%d",
--                       size, LIBUSB_DT_CONFIG_SIZE);
--              return LIBUSB_ERROR_IO;
--      }
--
-       usbi_parse_descriptor(buffer, "bbwbbbbb", config, host_endian);
 -      parse_descriptor(buffer, "bbwbbbbb", config);
--      if (config->bDescriptorType != LIBUSB_DT_CONFIG) {
-               usbi_err(ctx, "unexpected descriptor %x (expected %x)",
 -              usbi_err(ctx, "unexpected descriptor 0x%x (expected 0x%x)",
--                       config->bDescriptorType, LIBUSB_DT_CONFIG);
--              return LIBUSB_ERROR_IO;
-       }
-       if (config->bLength < LIBUSB_DT_CONFIG_SIZE) {
-               usbi_err(ctx, "invalid config bLength (%d)", config->bLength);
 -      } else if (config->bLength < LIBUSB_DT_CONFIG_SIZE) {
 -              usbi_err(ctx, "invalid config bLength (%u)", config->bLength);
--              return LIBUSB_ERROR_IO;
-       }
-       if (config->bLength > size) {
-               usbi_err(ctx, "short config descriptor read %d/%d",
 -      } else if (config->bLength > size) {
 -              usbi_err(ctx, "short config descriptor read %d/%u",
--                       size, config->bLength);
--              return LIBUSB_ERROR_IO;
-       }
-       if (config->bNumInterfaces > USB_MAXINTERFACES) {
-               usbi_err(ctx, "too many interfaces (%d)", config->bNumInterfaces);
 -      } else if (config->bNumInterfaces > USB_MAXINTERFACES) {
 -              usbi_err(ctx, "too many interfaces (%u)", config->bNumInterfaces);
--              return LIBUSB_ERROR_IO;
--      }
--
-       usb_interface = calloc(config->bNumInterfaces, sizeof(struct libusb_interface));
-       config->interface = usb_interface;
 -      usb_interface = calloc(config->bNumInterfaces, sizeof(*usb_interface));
--      if (!usb_interface)
--              return LIBUSB_ERROR_NO_MEM;
 -
 -      config->interface = usb_interface;
--
--      buffer += config->bLength;
--      size -= config->bLength;
-       config->extra = NULL;
-       config->extra_length = 0;
--
--      for (i = 0; i < config->bNumInterfaces; i++) {
--              int len;
-               unsigned char *begin;
 -              const uint8_t *begin;
--
--              /* Skip over the rest of the Class Specific or Vendor */
--              /*  Specific descriptors */
--              begin = buffer;
--              while (size >= DESC_HEADER_LENGTH) {
-                       usbi_parse_descriptor(buffer, "bb", &header, 0);
-                       if (header.bLength < DESC_HEADER_LENGTH) {
 -                      header = (const struct usbi_descriptor_header *)buffer;
 -                      if (header->bLength < DESC_HEADER_LENGTH) {
--                              usbi_err(ctx,
-                                        "invalid extra config desc len (%d)",
-                                        header.bLength);
 -                                       "invalid extra config desc len (%u)",
 -                                       header->bLength);
--                              r = LIBUSB_ERROR_IO;
--                              goto err;
-                       } else if (header.bLength > size) {
 -                      } else if (header->bLength > size) {
--                              usbi_warn(ctx,
-                                         "short extra config desc read %d/%d",
-                                         size, header.bLength);
-                               config->bNumInterfaces = (uint8_t)i;
 -                                        "short extra config desc read %d/%u",
 -                                        size, header->bLength);
 -                              config->bNumInterfaces = i;
--                              return size;
--                      }
--
--                      /* If we find another "proper" descriptor then we're done */
-                       if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
-                                       (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
-                                       (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
-                                       (header.bDescriptorType == LIBUSB_DT_DEVICE))
 -                      if (header->bDescriptorType == LIBUSB_DT_ENDPOINT ||
 -                          header->bDescriptorType == LIBUSB_DT_INTERFACE ||
 -                          header->bDescriptorType == LIBUSB_DT_CONFIG ||
 -                          header->bDescriptorType == LIBUSB_DT_DEVICE)
--                              break;
--
-                       usbi_dbg("skipping descriptor 0x%x", header.bDescriptorType);
-                       buffer += header.bLength;
-                       size -= header.bLength;
 -                      usbi_dbg("skipping descriptor 0x%x", header->bDescriptorType);
 -                      buffer += header->bLength;
 -                      size -= header->bLength;
--              }
--
--              /* Copy any unknown descriptors into a storage area for */
--              /*  drivers to later parse */
--              len = (int)(buffer - begin);
-               if (len) {
-                       /* FIXME: We should realloc and append here */
-                       if (!config->extra_length) {
-                               config->extra = malloc(len);
-                               if (!config->extra) {
-                                       r = LIBUSB_ERROR_NO_MEM;
-                                       goto err;
-                               }
 -              if (len > 0) {
 -                      uint8_t *extra = realloc((void *)config->extra,
 -                                               (size_t)(config->extra_length + len));
--
-                               memcpy((unsigned char *) config->extra, begin, len);
-                               config->extra_length = len;
 -                      if (!extra) {
 -                              r = LIBUSB_ERROR_NO_MEM;
 -                              goto err;
--                      }
 -
 -                      memcpy(extra + config->extra_length, begin, len);
 -                      config->extra = extra;
 -                      config->extra_length += len;
--              }
--
-               r = parse_interface(ctx, usb_interface + i, buffer, size, host_endian);
 -              r = parse_interface(ctx, usb_interface + i, buffer, size);
--              if (r < 0)
--                      goto err;
--              if (r == 0) {
-                       config->bNumInterfaces = (uint8_t)i;
 -                      config->bNumInterfaces = i;
--                      break;
--              }
--
--              buffer += r;
--              size -= r;
--      }
--
--      return size;
--
--err:
--      clear_configuration(config);
--      return r;
--}
--
--static int raw_desc_to_config(struct libusb_context *ctx,
-       unsigned char *buf, int size, int host_endian,
-       struct libusb_config_descriptor **config)
 -      const uint8_t *buf, int size, struct libusb_config_descriptor **config)
--{
-       struct libusb_config_descriptor *_config = malloc(sizeof(*_config));
 -      struct libusb_config_descriptor *_config = calloc(1, sizeof(*_config));
--      int r;
-       
 -
--      if (!_config)
--              return LIBUSB_ERROR_NO_MEM;
--
-       r = parse_configuration(ctx, _config, buf, size, host_endian);
 -      r = parse_configuration(ctx, _config, buf, size);
--      if (r < 0) {
--              usbi_err(ctx, "parse_configuration failed with error %d", r);
--              free(_config);
--              return r;
--      } else if (r > 0) {
--              usbi_warn(ctx, "still %d bytes of descriptor data left", r);
--      }
-       
 -
--      *config = _config;
--      return LIBUSB_SUCCESS;
--}
--
- int usbi_device_cache_descriptor(libusb_device *dev)
 -static int get_active_config_descriptor(struct libusb_device *dev,
 -      uint8_t *buffer, size_t size)
--{
-       int r, host_endian = 0;
 -      int r = usbi_backend.get_active_config_descriptor(dev, buffer, size);
--
-       r = usbi_backend.get_device_descriptor(dev, (unsigned char *) &dev->device_descriptor,
-                                               &host_endian);
--      if (r < 0)
--              return r;
--
-       if (!host_endian) {
-               dev->device_descriptor.bcdUSB = libusb_le16_to_cpu(dev->device_descriptor.bcdUSB);
-               dev->device_descriptor.idVendor = libusb_le16_to_cpu(dev->device_descriptor.idVendor);
-               dev->device_descriptor.idProduct = libusb_le16_to_cpu(dev->device_descriptor.idProduct);
-               dev->device_descriptor.bcdDevice = libusb_le16_to_cpu(dev->device_descriptor.bcdDevice);
 -      if (r < LIBUSB_DT_CONFIG_SIZE) {
 -              usbi_err(DEVICE_CTX(dev), "short config descriptor read %d/%d",
 -                       r, LIBUSB_DT_CONFIG_SIZE);
 -              return LIBUSB_ERROR_IO;
 -      } else if (r != (int)size) {
 -              usbi_warn(DEVICE_CTX(dev), "short config descriptor read %d/%d",
 -                       r, (int)size);
--      }
--
-       return LIBUSB_SUCCESS;
 -      return r;
 -}
 -
 -static int get_config_descriptor(struct libusb_device *dev, uint8_t config_idx,
 -      uint8_t *buffer, size_t size)
 -{
 -      int r = usbi_backend.get_config_descriptor(dev, config_idx, buffer, size);
 -
 -      if (r < 0)
 -              return r;
 -      if (r < LIBUSB_DT_CONFIG_SIZE) {
 -              usbi_err(DEVICE_CTX(dev), "short config descriptor read %d/%d",
 -                       r, LIBUSB_DT_CONFIG_SIZE);
 -              return LIBUSB_ERROR_IO;
 -      } else if (r != (int)size) {
 -              usbi_warn(DEVICE_CTX(dev), "short config descriptor read %d/%d",
 -                       r, (int)size);
 -      }
 -
 -      return r;
--}
--
--/** \ingroup libusb_desc
-- * Get the USB device descriptor for a given device.
-- *
-- * This is a non-blocking function; the device descriptor is cached in memory.
-- *
-- * Note since libusb-1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, this
-- * function always succeeds.
-- *
-- * \param dev the device
-- * \param desc output location for the descriptor data
-- * \returns 0 on success or a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_get_device_descriptor(libusb_device *dev,
--      struct libusb_device_descriptor *desc)
--{
-       usbi_dbg("");
-       memcpy((unsigned char *) desc, (unsigned char *) &dev->device_descriptor,
-              sizeof (dev->device_descriptor));
 -      usbi_dbg(" ");
 -      static_assert(sizeof(dev->device_descriptor) == LIBUSB_DT_DEVICE_SIZE,
 -                    "struct libusb_device_descriptor is not expected size");
 -      *desc = dev->device_descriptor;
--      return 0;
--}
--
--/** \ingroup libusb_desc
-- * Get the USB configuration descriptor for the currently active configuration.
-- * This is a non-blocking function which does not involve any requests being
-- * sent to the device.
-- *
-- * \param dev a device
-- * \param config output location for the USB configuration descriptor. Only
-- * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
-- * after use.
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
-- * \returns another LIBUSB_ERROR code on error
-- * \see libusb_get_config_descriptor
-- */
--int API_EXPORTED libusb_get_active_config_descriptor(libusb_device *dev,
--      struct libusb_config_descriptor **config)
--{
-       struct libusb_config_descriptor _config;
-       unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
-       unsigned char *buf = NULL;
-       int host_endian = 0;
 -      union usbi_config_desc_buf _config;
 -      uint16_t config_len;
 -      uint8_t *buf;
--      int r;
--
-       r = usbi_backend.get_active_config_descriptor(dev, tmp,
-               LIBUSB_DT_CONFIG_SIZE, &host_endian);
 -      r = get_active_config_descriptor(dev, _config.buf, sizeof(_config.buf));
--      if (r < 0)
--              return r;
-       if (r < LIBUSB_DT_CONFIG_SIZE) {
-               usbi_err(dev->ctx, "short config descriptor read %d/%d",
-                        r, LIBUSB_DT_CONFIG_SIZE);
-               return LIBUSB_ERROR_IO;
-       }
--
-       usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
-       buf = malloc(_config.wTotalLength);
 -      config_len = libusb_le16_to_cpu(_config.desc.wTotalLength);
 -      buf = malloc(config_len);
--      if (!buf)
--              return LIBUSB_ERROR_NO_MEM;
--
-       r = usbi_backend.get_active_config_descriptor(dev, buf,
-               _config.wTotalLength, &host_endian);
 -      r = get_active_config_descriptor(dev, buf, config_len);
--      if (r >= 0)
-               r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
 -              r = raw_desc_to_config(DEVICE_CTX(dev), buf, r, config);
--
--      free(buf);
--      return r;
--}
--
--/** \ingroup libusb_desc
-- * Get a USB configuration descriptor based on its index.
-- * This is a non-blocking function which does not involve any requests being
-- * sent to the device.
-- *
-- * \param dev a device
-- * \param config_index the index of the configuration you wish to retrieve
-- * \param config output location for the USB configuration descriptor. Only
-- * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
-- * after use.
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
-- * \returns another LIBUSB_ERROR code on error
-- * \see libusb_get_active_config_descriptor()
-- * \see libusb_get_config_descriptor_by_value()
-- */
--int API_EXPORTED libusb_get_config_descriptor(libusb_device *dev,
--      uint8_t config_index, struct libusb_config_descriptor **config)
--{
-       struct libusb_config_descriptor _config;
-       unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
-       unsigned char *buf = NULL;
-       int host_endian = 0;
 -      union usbi_config_desc_buf _config;
 -      uint16_t config_len;
 -      uint8_t *buf;
--      int r;
--
-       usbi_dbg("index %d", config_index);
-       if (config_index >= dev->num_configurations)
 -      usbi_dbg("index %u", config_index);
 -      if (config_index >= dev->device_descriptor.bNumConfigurations)
--              return LIBUSB_ERROR_NOT_FOUND;
--
-       r = usbi_backend.get_config_descriptor(dev, config_index, tmp,
-               LIBUSB_DT_CONFIG_SIZE, &host_endian);
 -      r = get_config_descriptor(dev, config_index, _config.buf, sizeof(_config.buf));
--      if (r < 0)
--              return r;
-       if (r < LIBUSB_DT_CONFIG_SIZE) {
-               usbi_err(dev->ctx, "short config descriptor read %d/%d",
-                        r, LIBUSB_DT_CONFIG_SIZE);
-               return LIBUSB_ERROR_IO;
-       }
--
-       usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
-       buf = malloc(_config.wTotalLength);
 -      config_len = libusb_le16_to_cpu(_config.desc.wTotalLength);
 -      buf = malloc(config_len);
--      if (!buf)
--              return LIBUSB_ERROR_NO_MEM;
--
-       r = usbi_backend.get_config_descriptor(dev, config_index, buf,
-               _config.wTotalLength, &host_endian);
 -      r = get_config_descriptor(dev, config_index, buf, config_len);
--      if (r >= 0)
-               r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
 -              r = raw_desc_to_config(DEVICE_CTX(dev), buf, r, config);
--
--      free(buf);
--      return r;
- }
- /* iterate through all configurations, returning the index of the configuration
-  * matching a specific bConfigurationValue in the idx output parameter, or -1
-  * if the config was not found.
-  * returns 0 on success or a LIBUSB_ERROR code
-  */
- int usbi_get_config_index_by_value(struct libusb_device *dev,
-       uint8_t bConfigurationValue, int *idx)
- {
-       uint8_t i;
-       usbi_dbg("value %d", bConfigurationValue);
-       for (i = 0; i < dev->num_configurations; i++) {
-               unsigned char tmp[6];
-               int host_endian;
-               int r = usbi_backend.get_config_descriptor(dev, i, tmp, sizeof(tmp),
-                       &host_endian);
-               if (r < 0) {
-                       *idx = -1;
-                       return r;
-               }
-               if (tmp[5] == bConfigurationValue) {
-                       *idx = i;
-                       return 0;
-               }
-       }
-       *idx = -1;
-       return 0;
--}
--
--/** \ingroup libusb_desc
-- * Get a USB configuration descriptor with a specific bConfigurationValue.
-- * This is a non-blocking function which does not involve any requests being
-- * sent to the device.
-- *
-- * \param dev a device
-- * \param bConfigurationValue the bConfigurationValue of the configuration you
-- * wish to retrieve
-- * \param config output location for the USB configuration descriptor. Only
-- * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
-- * after use.
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
-- * \returns another LIBUSB_ERROR code on error
-- * \see libusb_get_active_config_descriptor()
-- * \see libusb_get_config_descriptor()
-- */
--int API_EXPORTED libusb_get_config_descriptor_by_value(libusb_device *dev,
--      uint8_t bConfigurationValue, struct libusb_config_descriptor **config)
--{
-       int r, idx, host_endian;
-       unsigned char *buf = NULL;
 -      uint8_t idx;
 -      int r;
--
--      if (usbi_backend.get_config_descriptor_by_value) {
 -              void *buf;
 -
--              r = usbi_backend.get_config_descriptor_by_value(dev,
-                       bConfigurationValue, &buf, &host_endian);
 -                      bConfigurationValue, &buf);
--              if (r < 0)
--                      return r;
-               return raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
 -
 -              return raw_desc_to_config(DEVICE_CTX(dev), buf, r, config);
--      }
--
-       r = usbi_get_config_index_by_value(dev, bConfigurationValue, &idx);
-       if (r < 0)
-               return r;
-       else if (idx == -1)
-               return LIBUSB_ERROR_NOT_FOUND;
-       else
-               return libusb_get_config_descriptor(dev, (uint8_t) idx, config);
 -      usbi_dbg("value %u", bConfigurationValue);
 -      for (idx = 0; idx < dev->device_descriptor.bNumConfigurations; idx++) {
 -              union usbi_config_desc_buf _config;
 -
 -              r = get_config_descriptor(dev, idx, _config.buf, sizeof(_config.buf));
 -              if (r < 0)
 -                      return r;
 -
 -              if (_config.desc.bConfigurationValue == bConfigurationValue)
 -                      return libusb_get_config_descriptor(dev, idx, config);
 -      }
 -
 -      return LIBUSB_ERROR_NOT_FOUND;
--}
--
--/** \ingroup libusb_desc
-- * Free a configuration descriptor obtained from
-- * libusb_get_active_config_descriptor() or libusb_get_config_descriptor().
-- * It is safe to call this function with a NULL config parameter, in which
-- * case the function simply returns.
-- *
-- * \param config the configuration descriptor to free
-- */
--void API_EXPORTED libusb_free_config_descriptor(
--      struct libusb_config_descriptor *config)
--{
--      if (!config)
--              return;
--
--      clear_configuration(config);
--      free(config);
--}
--
--/** \ingroup libusb_desc
-- * Get an endpoints superspeed endpoint companion descriptor (if any)
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param endpoint endpoint descriptor from which to get the superspeed
-- * endpoint companion descriptor
-- * \param ep_comp output location for the superspeed endpoint companion
-- * descriptor. Only valid if 0 was returned. Must be freed with
-- * libusb_free_ss_endpoint_companion_descriptor() after use.
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
-- * \returns another LIBUSB_ERROR code on error
-- */
--int API_EXPORTED libusb_get_ss_endpoint_companion_descriptor(
-       struct libusb_context *ctx,
 -      libusb_context *ctx,
--      const struct libusb_endpoint_descriptor *endpoint,
--      struct libusb_ss_endpoint_companion_descriptor **ep_comp)
--{
-       struct usb_descriptor_header header;
 -      struct usbi_descriptor_header *header;
 -      const uint8_t *buffer = endpoint->extra;
--      int size = endpoint->extra_length;
-       const unsigned char *buffer = endpoint->extra;
--
--      *ep_comp = NULL;
--
--      while (size >= DESC_HEADER_LENGTH) {
-               usbi_parse_descriptor(buffer, "bb", &header, 0);
-               if (header.bLength < 2 || header.bLength > size) {
-                       usbi_err(ctx, "invalid descriptor length %d",
-                                header.bLength);
-                       return LIBUSB_ERROR_IO;
-               }
-               if (header.bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) {
-                       buffer += header.bLength;
-                       size -= header.bLength;
 -              header = (struct usbi_descriptor_header *)buffer;
 -              if (header->bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) {
 -                      if (header->bLength < DESC_HEADER_LENGTH) {
 -                              usbi_err(ctx, "invalid descriptor length %u",
 -                                       header->bLength);
 -                              return LIBUSB_ERROR_IO;
 -                      }
 -                      buffer += header->bLength;
 -                      size -= header->bLength;
--                      continue;
-               }
-               if (header.bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) {
-                       usbi_err(ctx, "invalid ss-ep-comp-desc length %d",
-                                header.bLength);
 -              } else if (header->bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) {
 -                      usbi_err(ctx, "invalid ss-ep-comp-desc length %u",
 -                               header->bLength);
 -                      return LIBUSB_ERROR_IO;
 -              } else if (header->bLength > size) {
 -                      usbi_err(ctx, "short ss-ep-comp-desc read %d/%u",
 -                               size, header->bLength);
--                      return LIBUSB_ERROR_IO;
--              }
 -
--              *ep_comp = malloc(sizeof(**ep_comp));
-               if (*ep_comp == NULL)
 -              if (!*ep_comp)
--                      return LIBUSB_ERROR_NO_MEM;
-               usbi_parse_descriptor(buffer, "bbbbw", *ep_comp, 0);
 -              parse_descriptor(buffer, "bbbbw", *ep_comp);
--              return LIBUSB_SUCCESS;
--      }
--      return LIBUSB_ERROR_NOT_FOUND;
--}
--
--/** \ingroup libusb_desc
-- * Free a superspeed endpoint companion descriptor obtained from
-- * libusb_get_ss_endpoint_companion_descriptor().
-- * It is safe to call this function with a NULL ep_comp parameter, in which
-- * case the function simply returns.
-- *
-- * \param ep_comp the superspeed endpoint companion descriptor to free
-- */
--void API_EXPORTED libusb_free_ss_endpoint_companion_descriptor(
--      struct libusb_ss_endpoint_companion_descriptor *ep_comp)
--{
--      free(ep_comp);
--}
--
--static int parse_bos(struct libusb_context *ctx,
--      struct libusb_bos_descriptor **bos,
-       unsigned char *buffer, int size, int host_endian)
 -      const uint8_t *buffer, int size)
--{
-       struct libusb_bos_descriptor bos_header, *_bos;
-       struct libusb_bos_dev_capability_descriptor dev_cap;
-       int i;
 -      struct libusb_bos_descriptor *_bos;
 -      const struct usbi_bos_descriptor *bos_desc;
 -      const struct usbi_descriptor_header *header;
 -      uint8_t i;
--
--      if (size < LIBUSB_DT_BOS_SIZE) {
--              usbi_err(ctx, "short bos descriptor read %d/%d",
--                       size, LIBUSB_DT_BOS_SIZE);
--              return LIBUSB_ERROR_IO;
--      }
--
-       usbi_parse_descriptor(buffer, "bbwb", &bos_header, host_endian);
-       if (bos_header.bDescriptorType != LIBUSB_DT_BOS) {
-               usbi_err(ctx, "unexpected descriptor %x (expected %x)",
-                        bos_header.bDescriptorType, LIBUSB_DT_BOS);
 -      bos_desc = (const struct usbi_bos_descriptor *)buffer;
 -      if (bos_desc->bDescriptorType != LIBUSB_DT_BOS) {
 -              usbi_err(ctx, "unexpected descriptor 0x%x (expected 0x%x)",
 -                       bos_desc->bDescriptorType, LIBUSB_DT_BOS);
--              return LIBUSB_ERROR_IO;
-       }
-       if (bos_header.bLength < LIBUSB_DT_BOS_SIZE) {
-               usbi_err(ctx, "invalid bos bLength (%d)", bos_header.bLength);
 -      } else if (bos_desc->bLength < LIBUSB_DT_BOS_SIZE) {
 -              usbi_err(ctx, "invalid bos bLength (%u)", bos_desc->bLength);
--              return LIBUSB_ERROR_IO;
-       }
-       if (bos_header.bLength > size) {
-               usbi_err(ctx, "short bos descriptor read %d/%d",
-                        size, bos_header.bLength);
 -      } else if (bos_desc->bLength > size) {
 -              usbi_err(ctx, "short bos descriptor read %d/%u",
 -                       size, bos_desc->bLength);
--              return LIBUSB_ERROR_IO;
--      }
--
-       _bos = calloc (1,
-               sizeof(*_bos) + bos_header.bNumDeviceCaps * sizeof(void *));
 -      _bos = calloc(1, sizeof(*_bos) + bos_desc->bNumDeviceCaps * sizeof(void *));
--      if (!_bos)
--              return LIBUSB_ERROR_NO_MEM;
--
-       usbi_parse_descriptor(buffer, "bbwb", _bos, host_endian);
-       buffer += bos_header.bLength;
-       size -= bos_header.bLength;
 -      parse_descriptor(buffer, "bbwb", _bos);
 -      buffer += _bos->bLength;
 -      size -= _bos->bLength;
--
--      /* Get the device capability descriptors */
-       for (i = 0; i < bos_header.bNumDeviceCaps; i++) {
 -      for (i = 0; i < _bos->bNumDeviceCaps; i++) {
--              if (size < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
--                      usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
--                                size, LIBUSB_DT_DEVICE_CAPABILITY_SIZE);
--                      break;
--              }
-               usbi_parse_descriptor(buffer, "bbb", &dev_cap, host_endian);
-               if (dev_cap.bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) {
-                       usbi_warn(ctx, "unexpected descriptor %x (expected %x)",
-                                 dev_cap.bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY);
 -              header = (const struct usbi_descriptor_header *)buffer;
 -              if (header->bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) {
 -                      usbi_warn(ctx, "unexpected descriptor 0x%x (expected 0x%x)",
 -                                header->bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY);
--                      break;
-               }
-               if (dev_cap.bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
-                       usbi_err(ctx, "invalid dev-cap bLength (%d)",
-                                dev_cap.bLength);
 -              } else if (header->bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
 -                      usbi_err(ctx, "invalid dev-cap bLength (%u)",
 -                               header->bLength);
--                      libusb_free_bos_descriptor(_bos);
--                      return LIBUSB_ERROR_IO;
-               }
-               if (dev_cap.bLength > size) {
-                       usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
-                                 size, dev_cap.bLength);
 -              } else if (header->bLength > size) {
 -                      usbi_warn(ctx, "short dev-cap descriptor read %d/%u",
 -                                size, header->bLength);
--                      break;
--              }
--
-               _bos->dev_capability[i] = malloc(dev_cap.bLength);
 -              _bos->dev_capability[i] = malloc(header->bLength);
--              if (!_bos->dev_capability[i]) {
--                      libusb_free_bos_descriptor(_bos);
--                      return LIBUSB_ERROR_NO_MEM;
--              }
-               memcpy(_bos->dev_capability[i], buffer, dev_cap.bLength);
-               buffer += dev_cap.bLength;
-               size -= dev_cap.bLength;
 -              memcpy(_bos->dev_capability[i], buffer, header->bLength);
 -              buffer += header->bLength;
 -              size -= header->bLength;
--      }
-       _bos->bNumDeviceCaps = (uint8_t)i;
 -      _bos->bNumDeviceCaps = i;
--      *bos = _bos;
--
--      return LIBUSB_SUCCESS;
--}
--
--/** \ingroup libusb_desc
-- * Get a Binary Object Store (BOS) descriptor
-- * This is a BLOCKING function, which will send requests to the device.
-- *
-- * \param dev_handle the handle of an open libusb device
-- * \param bos output location for the BOS descriptor. Only valid if 0 was returned.
-- * Must be freed with \ref libusb_free_bos_descriptor() after use.
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the device doesn't have a BOS descriptor
-- * \returns another LIBUSB_ERROR code on error
-- */
--int API_EXPORTED libusb_get_bos_descriptor(libusb_device_handle *dev_handle,
--      struct libusb_bos_descriptor **bos)
--{
-       struct libusb_bos_descriptor _bos;
-       uint8_t bos_header[LIBUSB_DT_BOS_SIZE] = {0};
-       unsigned char *bos_data = NULL;
-       const int host_endian = 0;
 -      union usbi_bos_desc_buf _bos;
 -      uint16_t bos_len;
 -      uint8_t *bos_data;
--      int r;
--
--      /* Read the BOS. This generates 2 requests on the bus,
--       * one for the header, and one for the full BOS */
-       r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_header,
-                                 LIBUSB_DT_BOS_SIZE);
 -      r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, _bos.buf, sizeof(_bos.buf));
--      if (r < 0) {
--              if (r != LIBUSB_ERROR_PIPE)
--                      usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r);
--              return r;
--      }
--      if (r < LIBUSB_DT_BOS_SIZE) {
--              usbi_err(HANDLE_CTX(dev_handle), "short BOS read %d/%d",
--                       r, LIBUSB_DT_BOS_SIZE);
--              return LIBUSB_ERROR_IO;
--      }
--
-       usbi_parse_descriptor(bos_header, "bbwb", &_bos, host_endian);
-       usbi_dbg("found BOS descriptor: size %d bytes, %d capabilities",
-                _bos.wTotalLength, _bos.bNumDeviceCaps);
-       bos_data = calloc(_bos.wTotalLength, 1);
-       if (bos_data == NULL)
 -      bos_len = libusb_le16_to_cpu(_bos.desc.wTotalLength);
 -      usbi_dbg("found BOS descriptor: size %u bytes, %u capabilities",
 -               bos_len, _bos.desc.bNumDeviceCaps);
 -      bos_data = calloc(1, bos_len);
 -      if (!bos_data)
--              return LIBUSB_ERROR_NO_MEM;
--
-       r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_data,
-                                 _bos.wTotalLength);
-       if (r >= 0)
-               r = parse_bos(HANDLE_CTX(dev_handle), bos, bos_data, r, host_endian);
-       else
 -      r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_data, bos_len);
 -      if (r >= 0) {
 -              if (r != (int)bos_len)
 -                      usbi_warn(HANDLE_CTX(dev_handle), "short BOS read %d/%u",
 -                                r, bos_len);
 -              r = parse_bos(HANDLE_CTX(dev_handle), bos, bos_data, r);
 -      } else {
--              usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r);
 -      }
--
--      free(bos_data);
--      return r;
--}
--
--/** \ingroup libusb_desc
-- * Free a BOS descriptor obtained from libusb_get_bos_descriptor().
-- * It is safe to call this function with a NULL bos parameter, in which
-- * case the function simply returns.
-- *
-- * \param bos the BOS descriptor to free
-- */
--void API_EXPORTED libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos)
--{
-       int i;
 -      uint8_t i;
--
--      if (!bos)
--              return;
--
--      for (i = 0; i < bos->bNumDeviceCaps; i++)
--              free(bos->dev_capability[i]);
--      free(bos);
--}
--
--/** \ingroup libusb_desc
-- * Get an USB 2.0 Extension descriptor
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
-- * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION
-- * LIBUSB_BT_USB_2_0_EXTENSION
-- * \param usb_2_0_extension output location for the USB 2.0 Extension
-- * descriptor. Only valid if 0 was returned. Must be freed with
-- * libusb_free_usb_2_0_extension_descriptor() after use.
-- * \returns 0 on success
-- * \returns a LIBUSB_ERROR code on error
-- */
--int API_EXPORTED libusb_get_usb_2_0_extension_descriptor(
-       struct libusb_context *ctx,
 -      libusb_context *ctx,
--      struct libusb_bos_dev_capability_descriptor *dev_cap,
--      struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension)
--{
--      struct libusb_usb_2_0_extension_descriptor *_usb_2_0_extension;
-       const int host_endian = 0;
--
--      if (dev_cap->bDevCapabilityType != LIBUSB_BT_USB_2_0_EXTENSION) {
-               usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
 -              usbi_err(ctx, "unexpected bDevCapabilityType 0x%x (expected 0x%x)",
--                       dev_cap->bDevCapabilityType,
--                       LIBUSB_BT_USB_2_0_EXTENSION);
--              return LIBUSB_ERROR_INVALID_PARAM;
-       }
-       if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) {
-               usbi_err(ctx, "short dev-cap descriptor read %d/%d",
 -      } else if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) {
 -              usbi_err(ctx, "short dev-cap descriptor read %u/%d",
--                       dev_cap->bLength, LIBUSB_BT_USB_2_0_EXTENSION_SIZE);
--              return LIBUSB_ERROR_IO;
--      }
--
--      _usb_2_0_extension = malloc(sizeof(*_usb_2_0_extension));
--      if (!_usb_2_0_extension)
--              return LIBUSB_ERROR_NO_MEM;
--
-       usbi_parse_descriptor((unsigned char *)dev_cap, "bbbd",
-                             _usb_2_0_extension, host_endian);
 -      parse_descriptor(dev_cap, "bbbd", _usb_2_0_extension);
--
--      *usb_2_0_extension = _usb_2_0_extension;
--      return LIBUSB_SUCCESS;
--}
--
--/** \ingroup libusb_desc
-- * Free a USB 2.0 Extension descriptor obtained from
-- * libusb_get_usb_2_0_extension_descriptor().
-- * It is safe to call this function with a NULL usb_2_0_extension parameter,
-- * in which case the function simply returns.
-- *
-- * \param usb_2_0_extension the USB 2.0 Extension descriptor to free
-- */
--void API_EXPORTED libusb_free_usb_2_0_extension_descriptor(
--      struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension)
--{
--      free(usb_2_0_extension);
--}
--
--/** \ingroup libusb_desc
-- * Get a SuperSpeed USB Device Capability descriptor
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
-- * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
-- * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
-- * \param ss_usb_device_cap output location for the SuperSpeed USB Device
-- * Capability descriptor. Only valid if 0 was returned. Must be freed with
-- * libusb_free_ss_usb_device_capability_descriptor() after use.
-- * \returns 0 on success
-- * \returns a LIBUSB_ERROR code on error
-- */
--int API_EXPORTED libusb_get_ss_usb_device_capability_descriptor(
-       struct libusb_context *ctx,
 -      libusb_context *ctx,
--      struct libusb_bos_dev_capability_descriptor *dev_cap,
--      struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap)
--{
--      struct libusb_ss_usb_device_capability_descriptor *_ss_usb_device_cap;
-       const int host_endian = 0;
--
--      if (dev_cap->bDevCapabilityType != LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) {
-               usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
 -              usbi_err(ctx, "unexpected bDevCapabilityType 0x%x (expected 0x%x)",
--                       dev_cap->bDevCapabilityType,
--                       LIBUSB_BT_SS_USB_DEVICE_CAPABILITY);
--              return LIBUSB_ERROR_INVALID_PARAM;
-       }
-       if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) {
-               usbi_err(ctx, "short dev-cap descriptor read %d/%d",
 -      } else if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) {
 -              usbi_err(ctx, "short dev-cap descriptor read %u/%d",
--                       dev_cap->bLength, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE);
--              return LIBUSB_ERROR_IO;
--      }
--
--      _ss_usb_device_cap = malloc(sizeof(*_ss_usb_device_cap));
--      if (!_ss_usb_device_cap)
--              return LIBUSB_ERROR_NO_MEM;
--
-       usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbwbbw",
-                             _ss_usb_device_cap, host_endian);
 -      parse_descriptor(dev_cap, "bbbbwbbw", _ss_usb_device_cap);
--
--      *ss_usb_device_cap = _ss_usb_device_cap;
--      return LIBUSB_SUCCESS;
--}
--
--/** \ingroup libusb_desc
-- * Free a SuperSpeed USB Device Capability descriptor obtained from
-- * libusb_get_ss_usb_device_capability_descriptor().
-- * It is safe to call this function with a NULL ss_usb_device_cap
-- * parameter, in which case the function simply returns.
-- *
-  * \param ss_usb_device_cap the USB 2.0 Extension descriptor to free
 - * \param ss_usb_device_cap the SuperSpeed USB Device Capability descriptor
 - * to free
-- */
--void API_EXPORTED libusb_free_ss_usb_device_capability_descriptor(
--      struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap)
--{
--      free(ss_usb_device_cap);
--}
--
--/** \ingroup libusb_desc
-- * Get a Container ID descriptor
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
-- * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID
-- * LIBUSB_BT_CONTAINER_ID
-- * \param container_id output location for the Container ID descriptor.
-- * Only valid if 0 was returned. Must be freed with
-- * libusb_free_container_id_descriptor() after use.
-- * \returns 0 on success
-- * \returns a LIBUSB_ERROR code on error
-- */
- int API_EXPORTED libusb_get_container_id_descriptor(struct libusb_context *ctx,
 -int API_EXPORTED libusb_get_container_id_descriptor(libusb_context *ctx,
--      struct libusb_bos_dev_capability_descriptor *dev_cap,
--      struct libusb_container_id_descriptor **container_id)
--{
--      struct libusb_container_id_descriptor *_container_id;
-       const int host_endian = 0;
--
--      if (dev_cap->bDevCapabilityType != LIBUSB_BT_CONTAINER_ID) {
-               usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
 -              usbi_err(ctx, "unexpected bDevCapabilityType 0x%x (expected 0x%x)",
--                       dev_cap->bDevCapabilityType,
--                       LIBUSB_BT_CONTAINER_ID);
--              return LIBUSB_ERROR_INVALID_PARAM;
-       }
-       if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) {
-               usbi_err(ctx, "short dev-cap descriptor read %d/%d",
 -      } else if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) {
 -              usbi_err(ctx, "short dev-cap descriptor read %u/%d",
--                       dev_cap->bLength, LIBUSB_BT_CONTAINER_ID_SIZE);
--              return LIBUSB_ERROR_IO;
--      }
--
--      _container_id = malloc(sizeof(*_container_id));
--      if (!_container_id)
--              return LIBUSB_ERROR_NO_MEM;
--
-       usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbu",
-                             _container_id, host_endian);
 -      parse_descriptor(dev_cap, "bbbbu", _container_id);
--
--      *container_id = _container_id;
--      return LIBUSB_SUCCESS;
--}
--
--/** \ingroup libusb_desc
-- * Free a Container ID descriptor obtained from
-- * libusb_get_container_id_descriptor().
-- * It is safe to call this function with a NULL container_id parameter,
-- * in which case the function simply returns.
-- *
-  * \param container_id the USB 2.0 Extension descriptor to free
 - * \param container_id the Container ID descriptor to free
-- */
--void API_EXPORTED libusb_free_container_id_descriptor(
--      struct libusb_container_id_descriptor *container_id)
--{
--      free(container_id);
--}
--
--/** \ingroup libusb_desc
-- * Retrieve a string descriptor in C style ASCII.
-- *
-- * Wrapper around libusb_get_string_descriptor(). Uses the first language
-- * supported by the device.
-- *
-- * \param dev_handle a device handle
-- * \param desc_index the index of the descriptor to retrieve
-- * \param data output buffer for ASCII string descriptor
-- * \param length size of data buffer
-- * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle,
--      uint8_t desc_index, unsigned char *data, int length)
--{
-       unsigned char tbuf[255]; /* Some devices choke on size > 255 */
 -      union usbi_string_desc_buf str;
--      int r, si, di;
-       uint16_t langid;
 -      uint16_t langid, wdata;
--
--      /* Asking for the zero'th index is special - it returns a string
--       * descriptor that contains all the language IDs supported by the
--       * device. Typically there aren't many - often only one. Language
--       * IDs are 16 bit numbers, and they start at the third byte in the
--       * descriptor. There's also no point in trying to read descriptor 0
--       * with this function. See USB 2.0 specification section 9.6.7 for
--       * more information.
--       */
--
--      if (desc_index == 0)
--              return LIBUSB_ERROR_INVALID_PARAM;
--
-       r = libusb_get_string_descriptor(dev_handle, 0, 0, tbuf, sizeof(tbuf));
 -      r = libusb_get_string_descriptor(dev_handle, 0, 0, str.buf, 4);
--      if (r < 0)
--              return r;
-       if (r < 4)
 -      else if (r != 4 || str.desc.bLength < 4)
--              return LIBUSB_ERROR_IO;
-       langid = tbuf[2] | (tbuf[3] << 8);
 -      else if (str.desc.bDescriptorType != LIBUSB_DT_STRING)
 -              return LIBUSB_ERROR_IO;
 -      else if (str.desc.bLength & 1)
 -              usbi_warn(HANDLE_CTX(dev_handle), "suspicious bLength %u for string descriptor", str.desc.bLength);
--
-       r = libusb_get_string_descriptor(dev_handle, desc_index, langid, tbuf,
-               sizeof(tbuf));
 -      langid = libusb_le16_to_cpu(str.desc.wData[0]);
 -      r = libusb_get_string_descriptor(dev_handle, desc_index, langid, str.buf, sizeof(str.buf));
--      if (r < 0)
--              return r;
-       if (tbuf[1] != LIBUSB_DT_STRING)
 -      else if (r < DESC_HEADER_LENGTH || str.desc.bLength > r)
--              return LIBUSB_ERROR_IO;
-       if (tbuf[0] > r)
 -      else if (str.desc.bDescriptorType != LIBUSB_DT_STRING)
--              return LIBUSB_ERROR_IO;
 -      else if ((str.desc.bLength & 1) || str.desc.bLength != r)
 -              usbi_warn(HANDLE_CTX(dev_handle), "suspicious bLength %u for string descriptor", str.desc.bLength);
--
--      di = 0;
-       for (si = 2; si < tbuf[0]; si += 2) {
 -      for (si = 2; si < str.desc.bLength; si += 2) {
--              if (di >= (length - 1))
--                      break;
--
-               if ((tbuf[si] & 0x80) || (tbuf[si + 1])) /* non-ASCII */
-                       data[di++] = '?';
 -              wdata = libusb_le16_to_cpu(str.desc.wData[di]);
 -              if (wdata < 0x80)
 -                      data[di++] = (unsigned char)wdata;
--              else
-                       data[di++] = tbuf[si];
 -                      data[di++] = '?'; /* non-ASCII */
--      }
--
--      data[di] = 0;
--      return di;
--}
diff --cc mac/libusb/hotplug.c
index a4320bc42e593917c65a9d83af11dfc1e0708512,e3e5e76e688d5772e5aca480a602bcd3401cf4a9..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,373 -1,397 +1,0 @@@
--/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
--/*
-- * Hotplug functions for libusb
-- * Copyright © 2012-2013 Nathan Hjelm <hjelmn@mac.com>
-- * Copyright © 2012-2013 Peter Stuge <peter@stuge.se>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
- #include <config.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #ifdef HAVE_SYS_TYPES_H
- #include <sys/types.h>
- #endif
- #include <assert.h>
--
--#include "libusbi.h"
--#include "hotplug.h"
--
--/**
-- * @defgroup libusb_hotplug Device hotplug event notification
-- * This page details how to use the libusb hotplug interface, where available.
-- *
-- * Be mindful that not all platforms currently implement hotplug notification and
-- * that you should first call on \ref libusb_has_capability() with parameter
-- * \ref LIBUSB_CAP_HAS_HOTPLUG to confirm that hotplug support is available.
-- *
-- * \page libusb_hotplug Device hotplug event notification
-- *
-- * \section hotplug_intro Introduction
-- *
-- * Version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, has added support
-- * for hotplug events on <b>some</b> platforms (you should test if your platform
-- * supports hotplug notification by calling \ref libusb_has_capability() with
-  * parameter \ref LIBUSB_CAP_HAS_HOTPLUG). 
 - * parameter \ref LIBUSB_CAP_HAS_HOTPLUG).
-- *
-- * This interface allows you to request notification for the arrival and departure
-- * of matching USB devices.
-- *
-- * To receive hotplug notification you register a callback by calling
-- * \ref libusb_hotplug_register_callback(). This function will optionally return
-- * a callback handle that can be passed to \ref libusb_hotplug_deregister_callback().
-- *
-- * A callback function must return an int (0 or 1) indicating whether the callback is
-- * expecting additional events. Returning 0 will rearm the callback and 1 will cause
-- * the callback to be deregistered. Note that when callbacks are called from
-- * libusb_hotplug_register_callback() because of the \ref LIBUSB_HOTPLUG_ENUMERATE
-  * flag, the callback return value is ignored, iow you cannot cause a callback
-  * to be deregistered by returning 1 when it is called from
 - * flag, the callback return value is ignored. In other words, you cannot cause a
 - * callback to be deregistered by returning 1 when it is called from
-- * libusb_hotplug_register_callback().
-- *
-- * Callbacks for a particular context are automatically deregistered by libusb_exit().
-- *
-- * As of 1.0.16 there are two supported hotplug events:
-- *  - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: A device has arrived and is ready to use
-- *  - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: A device has left and is no longer available
-- *
-- * A hotplug event can listen for either or both of these events.
-- *
-- * Note: If you receive notification that a device has left and you have any
-- * a libusb_device_handles for the device it is up to you to call libusb_close()
-- * on each device handle to free up any remaining resources associated with the device.
-- * Once a device has left any libusb_device_handle associated with the device
-- * are invalid and will remain so even if the device comes back.
-- *
-- * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED event it is considered
-- * safe to call any libusb function that takes a libusb_device. It also safe to
-- * open a device and submit asynchronous transfers. However, most other functions
-- * that take a libusb_device_handle are <b>not</b> safe to call. Examples of such
-- * functions are any of the \ref libusb_syncio "synchronous API" functions or the blocking
-- * functions that retrieve various \ref libusb_desc "USB descriptors". These functions must
-- * be used outside of the context of the hotplug callback.
-- *
-- * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT event the only safe function
-- * is libusb_get_device_descriptor().
-- *
-- * The following code provides an example of the usage of the hotplug interface:
--\code
--#include <stdio.h>
--#include <stdlib.h>
--#include <time.h>
--#include <libusb.h>
--
--static int count = 0;
--
--int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
--                     libusb_hotplug_event event, void *user_data) {
--  static libusb_device_handle *dev_handle = NULL;
--  struct libusb_device_descriptor desc;
--  int rc;
--
--  (void)libusb_get_device_descriptor(dev, &desc);
--
--  if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
--    rc = libusb_open(dev, &dev_handle);
--    if (LIBUSB_SUCCESS != rc) {
--      printf("Could not open USB device\n");
--    }
--  } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
--    if (dev_handle) {
--      libusb_close(dev_handle);
--      dev_handle = NULL;
--    }
--  } else {
--    printf("Unhandled event %d\n", event);
--  }
--  count++;
--
--  return 0;
--}
--
--int main (void) {
--  libusb_hotplug_callback_handle callback_handle;
--  int rc;
--
--  libusb_init(NULL);
--
--  rc = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
--                                        LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, 0x045a, 0x5005,
--                                        LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL,
--                                        &callback_handle);
--  if (LIBUSB_SUCCESS != rc) {
--    printf("Error creating a hotplug callback\n");
--    libusb_exit(NULL);
--    return EXIT_FAILURE;
--  }
--
--  while (count < 2) {
--    libusb_handle_events_completed(NULL, NULL);
--    nanosleep(&(struct timespec){0, 10000000UL}, NULL);
--  }
--
--  libusb_hotplug_deregister_callback(NULL, callback_handle);
--  libusb_exit(NULL);
--
--  return 0;
--}
--\endcode
-- */
 -
 -#define VALID_HOTPLUG_EVENTS                  \
 -       (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | \
 -        LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
 -
 -#define VALID_HOTPLUG_FLAGS                   \
 -       (LIBUSB_HOTPLUG_ENUMERATE)
--
--static int usbi_hotplug_match_cb(struct libusb_context *ctx,
--      struct libusb_device *dev, libusb_hotplug_event event,
--      struct libusb_hotplug_callback *hotplug_cb)
--{
--      if (!(hotplug_cb->flags & event)) {
--              return 0;
--      }
--
--      if ((hotplug_cb->flags & USBI_HOTPLUG_VENDOR_ID_VALID) &&
--          hotplug_cb->vendor_id != dev->device_descriptor.idVendor) {
--              return 0;
--      }
--
--      if ((hotplug_cb->flags & USBI_HOTPLUG_PRODUCT_ID_VALID) &&
--          hotplug_cb->product_id != dev->device_descriptor.idProduct) {
--              return 0;
--      }
--
--      if ((hotplug_cb->flags & USBI_HOTPLUG_DEV_CLASS_VALID) &&
--          hotplug_cb->dev_class != dev->device_descriptor.bDeviceClass) {
--              return 0;
--      }
--
--      return hotplug_cb->cb(ctx, dev, event, hotplug_cb->user_data);
--}
--
--void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev,
--      libusb_hotplug_event event)
--{
--      struct libusb_hotplug_callback *hotplug_cb, *next;
--      int ret;
--
--      usbi_mutex_lock(&ctx->hotplug_cbs_lock);
--
-       list_for_each_entry_safe(hotplug_cb, next, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) {
 -      for_each_hotplug_cb_safe(ctx, hotplug_cb, next) {
--              if (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE) {
--                      /* process deregistration in usbi_hotplug_deregister() */
--                      continue;
--              }
--
--              usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
--              ret = usbi_hotplug_match_cb(ctx, dev, event, hotplug_cb);
--              usbi_mutex_lock(&ctx->hotplug_cbs_lock);
--
--              if (ret) {
--                      list_del(&hotplug_cb->list);
--                      free(hotplug_cb);
--              }
--      }
--
--      usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
--}
--
--void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
--      libusb_hotplug_event event)
--{
-       int pending_events;
--      struct libusb_hotplug_message *message = calloc(1, sizeof(*message));
 -      unsigned int event_flags;
--
--      if (!message) {
--              usbi_err(ctx, "error allocating hotplug message");
--              return;
--      }
--
--      message->event = event;
--      message->device = dev;
--
--      /* Take the event data lock and add this message to the list.
--       * Only signal an event if there are no prior pending events. */
--      usbi_mutex_lock(&ctx->event_data_lock);
-       pending_events = usbi_pending_events(ctx);
 -      event_flags = ctx->event_flags;
 -      ctx->event_flags |= USBI_EVENT_HOTPLUG_MSG_PENDING;
--      list_add_tail(&message->list, &ctx->hotplug_msgs);
-       if (!pending_events)
-               usbi_signal_event(ctx);
 -      if (!event_flags)
 -              usbi_signal_event(&ctx->event);
--      usbi_mutex_unlock(&ctx->event_data_lock);
--}
--
--int API_EXPORTED libusb_hotplug_register_callback(libusb_context *ctx,
-       libusb_hotplug_event events, libusb_hotplug_flag flags,
 -      int events, int flags,
--      int vendor_id, int product_id, int dev_class,
--      libusb_hotplug_callback_fn cb_fn, void *user_data,
--      libusb_hotplug_callback_handle *callback_handle)
--{
--      struct libusb_hotplug_callback *new_callback;
--
--      /* check for sane values */
-       if ((!events || (~(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) & events)) ||
-           (flags && (~LIBUSB_HOTPLUG_ENUMERATE & flags)) ||
 -      if ((!events || (~VALID_HOTPLUG_EVENTS & events)) ||
 -          (~VALID_HOTPLUG_FLAGS & flags) ||
--          (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id && (~0xffff & vendor_id)) ||
--          (LIBUSB_HOTPLUG_MATCH_ANY != product_id && (~0xffff & product_id)) ||
--          (LIBUSB_HOTPLUG_MATCH_ANY != dev_class && (~0xff & dev_class)) ||
--          !cb_fn) {
--              return LIBUSB_ERROR_INVALID_PARAM;
--      }
--
--      /* check for hotplug support */
--      if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
--              return LIBUSB_ERROR_NOT_SUPPORTED;
--      }
--
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--
--      new_callback = calloc(1, sizeof(*new_callback));
--      if (!new_callback) {
--              return LIBUSB_ERROR_NO_MEM;
--      }
--
--      new_callback->flags = (uint8_t)events;
--      if (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id) {
--              new_callback->flags |= USBI_HOTPLUG_VENDOR_ID_VALID;
--              new_callback->vendor_id = (uint16_t)vendor_id;
--      }
--      if (LIBUSB_HOTPLUG_MATCH_ANY != product_id) {
--              new_callback->flags |= USBI_HOTPLUG_PRODUCT_ID_VALID;
--              new_callback->product_id = (uint16_t)product_id;
--      }
--      if (LIBUSB_HOTPLUG_MATCH_ANY != dev_class) {
--              new_callback->flags |= USBI_HOTPLUG_DEV_CLASS_VALID;
--              new_callback->dev_class = (uint8_t)dev_class;
--      }
--      new_callback->cb = cb_fn;
--      new_callback->user_data = user_data;
--
--      usbi_mutex_lock(&ctx->hotplug_cbs_lock);
--
--      /* protect the handle by the context hotplug lock */
--      new_callback->handle = ctx->next_hotplug_cb_handle++;
--
--      /* handle the unlikely case of overflow */
--      if (ctx->next_hotplug_cb_handle < 0)
--              ctx->next_hotplug_cb_handle = 1;
--
--      list_add(&new_callback->list, &ctx->hotplug_cbs);
--
--      usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
--
--      usbi_dbg("new hotplug cb %p with handle %d", new_callback, new_callback->handle);
--
--      if ((flags & LIBUSB_HOTPLUG_ENUMERATE) && (events & LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)) {
--              ssize_t i, len;
--              struct libusb_device **devs;
--
--              len = libusb_get_device_list(ctx, &devs);
--              if (len < 0) {
--                      libusb_hotplug_deregister_callback(ctx,
--                                                      new_callback->handle);
--                      return (int)len;
--              }
--
--              for (i = 0; i < len; i++) {
--                      usbi_hotplug_match_cb(ctx, devs[i],
--                                      LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
--                                      new_callback);
--              }
--
--              libusb_free_device_list(devs, 1);
--      }
--
--
--      if (callback_handle)
--              *callback_handle = new_callback->handle;
--
--      return LIBUSB_SUCCESS;
--}
--
- void API_EXPORTED libusb_hotplug_deregister_callback(struct libusb_context *ctx,
 -void API_EXPORTED libusb_hotplug_deregister_callback(libusb_context *ctx,
--      libusb_hotplug_callback_handle callback_handle)
--{
--      struct libusb_hotplug_callback *hotplug_cb;
--      int deregistered = 0;
--
--      /* check for hotplug support */
--      if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
--              return;
--      }
-       USBI_GET_CONTEXT(ctx);
--
--      usbi_dbg("deregister hotplug cb %d", callback_handle);
 -
 -      ctx = usbi_get_context(ctx);
--
--      usbi_mutex_lock(&ctx->hotplug_cbs_lock);
-       list_for_each_entry(hotplug_cb, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) {
 -      for_each_hotplug_cb(ctx, hotplug_cb) {
--              if (callback_handle == hotplug_cb->handle) {
--                      /* Mark this callback for deregistration */
--                      hotplug_cb->flags |= USBI_HOTPLUG_NEEDS_FREE;
--                      deregistered = 1;
--              }
--      }
--      usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
--
--      if (deregistered) {
-               int pending_events;
 -              unsigned int event_flags;
--
--              usbi_mutex_lock(&ctx->event_data_lock);
-               pending_events = usbi_pending_events(ctx);
 -              event_flags = ctx->event_flags;
--              ctx->event_flags |= USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
-               if (!pending_events)
-                       usbi_signal_event(ctx);
 -              if (!event_flags)
 -                      usbi_signal_event(&ctx->event);
--              usbi_mutex_unlock(&ctx->event_data_lock);
 -      }
 -}
 -
 -DEFAULT_VISIBILITY
 -void * LIBUSB_CALL libusb_hotplug_get_user_data(libusb_context *ctx,
 -      libusb_hotplug_callback_handle callback_handle)
 -{
 -      struct libusb_hotplug_callback *hotplug_cb;
 -      void *user_data = NULL;
 -
 -      /* check for hotplug support */
 -      if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
 -              return NULL;
 -      }
 -
 -      usbi_dbg("get hotplug user data %d", callback_handle);
 -
 -      ctx = usbi_get_context(ctx);
 -
 -      usbi_mutex_lock(&ctx->hotplug_cbs_lock);
 -      for_each_hotplug_cb(ctx, hotplug_cb) {
 -              if (callback_handle == hotplug_cb->handle) {
 -                      user_data = hotplug_cb->user_data;
 -              }
--      }
 -      usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
 -
 -      return user_data;
--}
--
--void usbi_hotplug_deregister(struct libusb_context *ctx, int forced)
--{
--      struct libusb_hotplug_callback *hotplug_cb, *next;
--
--      usbi_mutex_lock(&ctx->hotplug_cbs_lock);
-       list_for_each_entry_safe(hotplug_cb, next, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) {
 -      for_each_hotplug_cb_safe(ctx, hotplug_cb, next) {
--              if (forced || (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE)) {
--                      usbi_dbg("freeing hotplug cb %p with handle %d", hotplug_cb,
--                               hotplug_cb->handle);
--                      list_del(&hotplug_cb->list);
--                      free(hotplug_cb);
--              }
--      }
--      usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
--}
diff --cc mac/libusb/hotplug.h
index dbadbcb93d54a766ffe685b94775dd0f2458bbf5,161f7e5fcde20676a9b90d6d31d55e0ae561ec40..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,99 -1,105 +1,0 @@@
--/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
--/*
-- * Hotplug support for libusb
-- * Copyright © 2012-2013 Nathan Hjelm <hjelmn@mac.com>
-- * Copyright © 2012-2013 Peter Stuge <peter@stuge.se>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
--#ifndef USBI_HOTPLUG_H
--#define USBI_HOTPLUG_H
--
--#include "libusbi.h"
--
--enum usbi_hotplug_flags {
--      /* This callback is interested in device arrivals */
--      USBI_HOTPLUG_DEVICE_ARRIVED = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
--
--      /* This callback is interested in device removals */
--      USBI_HOTPLUG_DEVICE_LEFT = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
--
--      /* IMPORTANT: The values for the below entries must start *after*
--       * the highest value of the above entries!!!
--       */
--
--      /* The vendor_id field is valid for matching */
-       USBI_HOTPLUG_VENDOR_ID_VALID = (1 << 3),
 -      USBI_HOTPLUG_VENDOR_ID_VALID = (1U << 3),
--
--      /* The product_id field is valid for matching */
-       USBI_HOTPLUG_PRODUCT_ID_VALID = (1 << 4),
 -      USBI_HOTPLUG_PRODUCT_ID_VALID = (1U << 4),
--
--      /* The dev_class field is valid for matching */
-       USBI_HOTPLUG_DEV_CLASS_VALID = (1 << 5),
 -      USBI_HOTPLUG_DEV_CLASS_VALID = (1U << 5),
--
--      /* This callback has been unregistered and needs to be freed */
-       USBI_HOTPLUG_NEEDS_FREE = (1 << 6),
 -      USBI_HOTPLUG_NEEDS_FREE = (1U << 6),
--};
--
--/** \ingroup hotplug
-- * The hotplug callback structure. The user populates this structure with
-- * libusb_hotplug_prepare_callback() and then calls libusb_hotplug_register_callback()
-- * to receive notification of hotplug events.
-- */
--struct libusb_hotplug_callback {
--      /** Flags that control how this callback behaves */
--      uint8_t flags;
--
--      /** Vendor ID to match (if flags says this is valid) */
--      uint16_t vendor_id;
--
--      /** Product ID to match (if flags says this is valid) */
--      uint16_t product_id;
--
--      /** Device class to match (if flags says this is valid) */
--      uint8_t dev_class;
--
--      /** Callback function to invoke for matching event/device */
--      libusb_hotplug_callback_fn cb;
--
--      /** Handle for this callback (used to match on deregister) */
--      libusb_hotplug_callback_handle handle;
--
--      /** User data that will be passed to the callback function */
--      void *user_data;
--
--      /** List this callback is registered in (ctx->hotplug_cbs) */
--      struct list_head list;
--};
--
--struct libusb_hotplug_message {
--      /** The hotplug event that occurred */
--      libusb_hotplug_event event;
--
--      /** The device for which this hotplug event occurred */
--      struct libusb_device *device;
--
--      /** List this message is contained in (ctx->hotplug_msgs) */
--      struct list_head list;
--};
 -
 -#define for_each_hotplug_cb(ctx, c) \
 -      for_each_helper(c, &(ctx)->hotplug_cbs, struct libusb_hotplug_callback)
 -
 -#define for_each_hotplug_cb_safe(ctx, c, n) \
 -      for_each_safe_helper(c, n, &(ctx)->hotplug_cbs, struct libusb_hotplug_callback)
--
--void usbi_hotplug_deregister(struct libusb_context *ctx, int forced);
--void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev,
-                       libusb_hotplug_event event);
 -      libusb_hotplug_event event);
--void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
-                       libusb_hotplug_event event);
 -      libusb_hotplug_event event);
--
--#endif
diff --cc mac/libusb/io.c
index a03bfaae1a9e21b352f79c72e4b92ee4a6b71e5d,0e960ddfddd5292db40d8829084079eb081ad69d..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2822 -1,2833 +1,0 @@@
--/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
--/*
-- * I/O functions for libusb
-- * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
-- * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
 - * Copyright © 2019 Nathan Hjelm <hjelmn@cs.umm.edu>
 - * Copyright © 2019 Google LLC. All rights reserved.
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
- #include <config.h>
- #include <assert.h>
- #include <errno.h>
- #include <stdint.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #ifdef HAVE_SYS_TIME_H
- #include <sys/time.h>
- #endif
- #ifdef USBI_TIMERFD_AVAILABLE
- #include <sys/timerfd.h>
- #endif
--
--#include "libusbi.h"
--#include "hotplug.h"
--
--/**
-- * \page libusb_io Synchronous and asynchronous device I/O
-- *
-- * \section io_intro Introduction
-- *
-- * If you're using libusb in your application, you're probably wanting to
-- * perform I/O with devices - you want to perform USB data transfers.
-- *
-- * libusb offers two separate interfaces for device I/O. This page aims to
-- * introduce the two in order to help you decide which one is more suitable
-- * for your application. You can also choose to use both interfaces in your
-- * application by considering each transfer on a case-by-case basis.
-- *
-- * Once you have read through the following discussion, you should consult the
-- * detailed API documentation pages for the details:
-- * - \ref libusb_syncio
-- * - \ref libusb_asyncio
-- *
-- * \section theory Transfers at a logical level
-- *
-- * At a logical level, USB transfers typically happen in two parts. For
-- * example, when reading data from a endpoint:
-- * -# A request for data is sent to the device
-- * -# Some time later, the incoming data is received by the host
-- *
-- * or when writing data to an endpoint:
-- *
-- * -# The data is sent to the device
-- * -# Some time later, the host receives acknowledgement from the device that
-- *    the data has been transferred.
-- *
-- * There may be an indefinite delay between the two steps. Consider a
-- * fictional USB input device with a button that the user can press. In order
-- * to determine when the button is pressed, you would likely submit a request
-- * to read data on a bulk or interrupt endpoint and wait for data to arrive.
-- * Data will arrive when the button is pressed by the user, which is
-- * potentially hours later.
-- *
-- * libusb offers both a synchronous and an asynchronous interface to performing
-- * USB transfers. The main difference is that the synchronous interface
-- * combines both steps indicated above into a single function call, whereas
-- * the asynchronous interface separates them.
-- *
-- * \section sync The synchronous interface
-- *
-- * The synchronous I/O interface allows you to perform a USB transfer with
-- * a single function call. When the function call returns, the transfer has
-- * completed and you can parse the results.
-- *
-  * If you have used the libusb-0.1 before, this I/O style will seem familar to
 - * If you have used the libusb-0.1 before, this I/O style will seem familiar to
-- * you. libusb-0.1 only offered a synchronous interface.
-- *
-- * In our input device example, to read button presses you might write code
-- * in the following style:
--\code
--unsigned char data[4];
--int actual_length;
--int r = libusb_bulk_transfer(dev_handle, LIBUSB_ENDPOINT_IN, data, sizeof(data), &actual_length, 0);
--if (r == 0 && actual_length == sizeof(data)) {
--      // results of the transaction can now be found in the data buffer
--      // parse them here and report button press
--} else {
--      error();
--}
--\endcode
-- *
-- * The main advantage of this model is simplicity: you did everything with
-- * a single simple function call.
-- *
-- * However, this interface has its limitations. Your application will sleep
-- * inside libusb_bulk_transfer() until the transaction has completed. If it
-- * takes the user 3 hours to press the button, your application will be
-- * sleeping for that long. Execution will be tied up inside the library -
-- * the entire thread will be useless for that duration.
-- *
-  * Another issue is that by tieing up the thread with that single transaction
 - * Another issue is that by tying up the thread with that single transaction
-- * there is no possibility of performing I/O with multiple endpoints and/or
-- * multiple devices simultaneously, unless you resort to creating one thread
-- * per transaction.
-- *
-- * Additionally, there is no opportunity to cancel the transfer after the
-- * request has been submitted.
-- *
-- * For details on how to use the synchronous API, see the
-- * \ref libusb_syncio "synchronous I/O API documentation" pages.
-- *
-- * \section async The asynchronous interface
-- *
-- * Asynchronous I/O is the most significant new feature in libusb-1.0.
-- * Although it is a more complex interface, it solves all the issues detailed
-- * above.
-- *
-- * Instead of providing which functions that block until the I/O has complete,
-- * libusb's asynchronous interface presents non-blocking functions which
-- * begin a transfer and then return immediately. Your application passes a
-- * callback function pointer to this non-blocking function, which libusb will
-- * call with the results of the transaction when it has completed.
-- *
-- * Transfers which have been submitted through the non-blocking functions
-- * can be cancelled with a separate function call.
-- *
-- * The non-blocking nature of this interface allows you to be simultaneously
-- * performing I/O to multiple endpoints on multiple devices, without having
-- * to use threads.
-- *
-- * This added flexibility does come with some complications though:
-- * - In the interest of being a lightweight library, libusb does not create
-- * threads and can only operate when your application is calling into it. Your
-- * application must call into libusb from it's main loop when events are ready
-- * to be handled, or you must use some other scheme to allow libusb to
-- * undertake whatever work needs to be done.
-- * - libusb also needs to be called into at certain fixed points in time in
-- * order to accurately handle transfer timeouts.
-- * - Memory handling becomes more complex. You cannot use stack memory unless
-- * the function with that stack is guaranteed not to return until the transfer
-- * callback has finished executing.
-- * - You generally lose some linearity from your code flow because submitting
-- * the transfer request is done in a separate function from where the transfer
-- * results are handled. This becomes particularly obvious when you want to
-- * submit a second transfer based on the results of an earlier transfer.
-- *
-- * Internally, libusb's synchronous interface is expressed in terms of function
-- * calls to the asynchronous interface.
-- *
-- * For details on how to use the asynchronous API, see the
-- * \ref libusb_asyncio "asynchronous I/O API" documentation pages.
-- */
--
--
--/**
-- * \page libusb_packetoverflow Packets and overflows
-- *
-- * \section packets Packet abstraction
-- *
-- * The USB specifications describe how data is transmitted in packets, with
-- * constraints on packet size defined by endpoint descriptors. The host must
-- * not send data payloads larger than the endpoint's maximum packet size.
-- *
-- * libusb and the underlying OS abstract out the packet concept, allowing you
-- * to request transfers of any size. Internally, the request will be divided
-- * up into correctly-sized packets. You do not have to be concerned with
-- * packet sizes, but there is one exception when considering overflows.
-- *
-- * \section overflow Bulk/interrupt transfer overflows
-- *
-- * When requesting data on a bulk endpoint, libusb requires you to supply a
-- * buffer and the maximum number of bytes of data that libusb can put in that
-- * buffer. However, the size of the buffer is not communicated to the device -
-- * the device is just asked to send any amount of data.
-- *
-- * There is no problem if the device sends an amount of data that is less than
-- * or equal to the buffer size. libusb reports this condition to you through
-- * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length"
-- * field.
-- *
-- * Problems may occur if the device attempts to send more data than can fit in
-- * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but
-- * other behaviour is largely undefined: actual_length may or may not be
-- * accurate, the chunk of data that can fit in the buffer (before overflow)
-- * may or may not have been transferred.
-- *
-- * Overflows are nasty, but can be avoided. Even though you were told to
-- * ignore packets above, think about the lower level details: each transfer is
-- * split into packets (typically small, with a maximum size of 512 bytes).
-- * Overflows can only happen if the final packet in an incoming data transfer
-- * is smaller than the actual packet that the device wants to transfer.
-- * Therefore, you will never see an overflow if your transfer buffer size is a
-- * multiple of the endpoint's packet size: the final packet will either
-- * fill up completely or will be only partially filled.
-- */
--
--/**
-- * @defgroup libusb_asyncio Asynchronous device I/O
-- *
-- * This page details libusb's asynchronous (non-blocking) API for USB device
-- * I/O. This interface is very powerful but is also quite complex - you will
-- * need to read this page carefully to understand the necessary considerations
-- * and issues surrounding use of this interface. Simplistic applications
-- * may wish to consider the \ref libusb_syncio "synchronous I/O API" instead.
-- *
-- * The asynchronous interface is built around the idea of separating transfer
-- * submission and handling of transfer completion (the synchronous model
-- * combines both of these into one). There may be a long delay between
-- * submission and completion, however the asynchronous submission function
-- * is non-blocking so will return control to your application during that
-- * potentially long delay.
-- *
-- * \section asyncabstraction Transfer abstraction
-- *
-- * For the asynchronous I/O, libusb implements the concept of a generic
-- * transfer entity for all types of I/O (control, bulk, interrupt,
-- * isochronous). The generic transfer object must be treated slightly
-- * differently depending on which type of I/O you are performing with it.
-- *
-- * This is represented by the public libusb_transfer structure type.
-- *
-- * \section asynctrf Asynchronous transfers
-- *
-- * We can view asynchronous I/O as a 5 step process:
-- * -# <b>Allocation</b>: allocate a libusb_transfer
-- * -# <b>Filling</b>: populate the libusb_transfer instance with information
-- *    about the transfer you wish to perform
-- * -# <b>Submission</b>: ask libusb to submit the transfer
-- * -# <b>Completion handling</b>: examine transfer results in the
-- *    libusb_transfer structure
-- * -# <b>Deallocation</b>: clean up resources
-- *
-- *
-- * \subsection asyncalloc Allocation
-- *
-- * This step involves allocating memory for a USB transfer. This is the
-- * generic transfer object mentioned above. At this stage, the transfer
-- * is "blank" with no details about what type of I/O it will be used for.
-- *
-- * Allocation is done with the libusb_alloc_transfer() function. You must use
-- * this function rather than allocating your own transfers.
-- *
-- * \subsection asyncfill Filling
-- *
-- * This step is where you take a previously allocated transfer and fill it
-- * with information to determine the message type and direction, data buffer,
-- * callback function, etc.
-- *
-- * You can either fill the required fields yourself or you can use the
-- * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
-- * and libusb_fill_interrupt_transfer().
-- *
-- * \subsection asyncsubmit Submission
-- *
-- * When you have allocated a transfer and filled it, you can submit it using
-- * libusb_submit_transfer(). This function returns immediately but can be
-- * regarded as firing off the I/O request in the background.
-- *
-- * \subsection asynccomplete Completion handling
-- *
-- * After a transfer has been submitted, one of four things can happen to it:
-- *
-- * - The transfer completes (i.e. some data was transferred)
-- * - The transfer has a timeout and the timeout expires before all data is
-- * transferred
-- * - The transfer fails due to an error
-- * - The transfer is cancelled
-- *
-- * Each of these will cause the user-specified transfer callback function to
-- * be invoked. It is up to the callback function to determine which of the
-- * above actually happened and to act accordingly.
-- *
-- * The user-specified callback is passed a pointer to the libusb_transfer
-- * structure which was used to setup and submit the transfer. At completion
-- * time, libusb has populated this structure with results of the transfer:
-- * success or failure reason, number of bytes of data transferred, etc. See
-- * the libusb_transfer structure documentation for more information.
-- *
-- * <b>Important Note</b>: The user-specified callback is called from an event
-- * handling context. It is therefore important that no calls are made into
-- * libusb that will attempt to perform any event handling. Examples of such
-- * functions are any listed in the \ref libusb_syncio "synchronous API" and any of
-- * the blocking functions that retrieve \ref libusb_desc "USB descriptors".
-- *
-- * \subsection Deallocation
-- *
-- * When a transfer has completed (i.e. the callback function has been invoked),
-- * you are advised to free the transfer (unless you wish to resubmit it, see
-- * below). Transfers are deallocated with libusb_free_transfer().
-- *
-- * It is undefined behaviour to free a transfer which has not completed.
-- *
-- * \section asyncresubmit Resubmission
-- *
-- * You may be wondering why allocation, filling, and submission are all
-- * separated above where they could reasonably be combined into a single
-- * operation.
-- *
-- * The reason for separation is to allow you to resubmit transfers without
-- * having to allocate new ones every time. This is especially useful for
-- * common situations dealing with interrupt endpoints - you allocate one
-- * transfer, fill and submit it, and when it returns with results you just
-- * resubmit it for the next interrupt.
-- *
-- * \section asynccancel Cancellation
-- *
-- * Another advantage of using the asynchronous interface is that you have
-- * the ability to cancel transfers which have not yet completed. This is
-- * done by calling the libusb_cancel_transfer() function.
-- *
-- * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
-- * cancellation actually completes, the transfer's callback function will
-- * be invoked, and the callback function should check the transfer status to
-- * determine that it was cancelled.
-- *
-- * Freeing the transfer after it has been cancelled but before cancellation
-- * has completed will result in undefined behaviour.
-- *
 - * \attention
-- * When a transfer is cancelled, some of the data may have been transferred.
-  * libusb will communicate this to you in the transfer callback. Do not assume
-  * that no data was transferred.
 - * libusb will communicate this to you in the transfer callback.
 - * <b>Do not assume that no data was transferred.</b>
 - *
 - * \section asyncpartial Partial data transfer resulting from cancellation
 - *
 - * As noted above, some of the data may have been transferred at the time a
 - * transfer is cancelled. It is helpful to see how this is possible if you
 - * consider a bulk transfer to an endpoint with a packet size of 64 bytes.
 - * Supposing you submit a 512-byte transfer to this endpoint, the operating
 - * system will divide this transfer up into 8 separate 64-byte frames that the
 - * host controller will schedule for the device to transfer data. If this
 - * transfer is cancelled while the device is transferring data, a subset of
 - * these frames may be descheduled from the host controller before the device
 - * has the opportunity to finish transferring data to the host.
 - *
 - * What your application should do with a partial data transfer is a policy
 - * decision; there is no single answer that satisfies the needs of every
 - * application. The data that was successfully transferred should be
 - * considered entirely valid, but your application must decide what to do with
 - * the remaining data that was not transferred. Some possible actions to take
 - * are:
 - * - Resubmit another transfer for the remaining data, possibly with a shorter
 - *   timeout
 - * - Discard the partially transferred data and report an error
 - *
 - * \section asynctimeout Timeouts
 - *
 - * When a transfer times out, libusb internally notes this and attempts to
 - * cancel the transfer. As noted in \ref asyncpartial "above", it is possible
 - * that some of the data may actually have been transferred. Your application
 - * should <b>always</b> check how much data was actually transferred once the
 - * transfer completes and act accordingly.
-- *
-- * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints
-- *
-- * If your device does not have predictable transfer sizes (or it misbehaves),
-- * your application may submit a request for data on an IN endpoint which is
-- * smaller than the data that the device wishes to send. In some circumstances
-- * this will cause an overflow, which is a nasty condition to deal with. See
-- * the \ref libusb_packetoverflow page for discussion.
-- *
-- * \section asyncctrl Considerations for control transfers
-- *
-- * The <tt>libusb_transfer</tt> structure is generic and hence does not
-- * include specific fields for the control-specific setup packet structure.
-- *
-- * In order to perform a control transfer, you must place the 8-byte setup
-- * packet at the start of the data buffer. To simplify this, you could
-- * cast the buffer pointer to type struct libusb_control_setup, or you can
-- * use the helper function libusb_fill_control_setup().
-- *
-- * The wLength field placed in the setup packet must be the length you would
-- * expect to be sent in the setup packet: the length of the payload that
-- * follows (or the expected maximum number of bytes to receive). However,
-- * the length field of the libusb_transfer object must be the length of
-- * the data buffer - i.e. it should be wLength <em>plus</em> the size of
-- * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
-- *
-- * If you use the helper functions, this is simplified for you:
-- * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
-- * data you are sending/requesting.
-- * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
-- * request size as the wLength value (i.e. do not include the extra space you
-- * allocated for the control setup).
-- * -# If this is a host-to-device transfer, place the data to be transferred
-- * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
-- * -# Call libusb_fill_control_transfer() to associate the data buffer with
-- * the transfer (and to set the remaining details such as callback and timeout).
-- *   - Note that there is no parameter to set the length field of the transfer.
-- *     The length is automatically inferred from the wLength field of the setup
-- *     packet.
-- * -# Submit the transfer.
-- *
-- * The multi-byte control setup fields (wValue, wIndex and wLength) must
-- * be given in little-endian byte order (the endianness of the USB bus).
-- * Endianness conversion is transparently handled by
-- * libusb_fill_control_setup() which is documented to accept host-endian
-- * values.
-- *
-- * Further considerations are needed when handling transfer completion in
-- * your callback function:
-- * - As you might expect, the setup packet will still be sitting at the start
-- * of the data buffer.
-- * - If this was a device-to-host transfer, the received data will be sitting
-- * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
-- * - The actual_length field of the transfer structure is relative to the
-- * wLength of the setup packet, rather than the size of the data buffer. So,
-- * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
-- * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
-  * transferred in entirity.
 - * transferred in entirety.
-- *
-- * To simplify parsing of setup packets and obtaining the data from the
-- * correct offset, you may wish to use the libusb_control_transfer_get_data()
-- * and libusb_control_transfer_get_setup() functions within your transfer
-- * callback.
-- *
-- * Even though control endpoints do not halt, a completed control transfer
-- * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
-- * request was not supported.
-- *
-- * \section asyncintr Considerations for interrupt transfers
-- *
-- * All interrupt transfers are performed using the polling interval presented
-- * by the bInterval value of the endpoint descriptor.
-- *
-- * \section asynciso Considerations for isochronous transfers
-- *
-- * Isochronous transfers are more complicated than transfers to
-- * non-isochronous endpoints.
-- *
-- * To perform I/O to an isochronous endpoint, allocate the transfer by calling
-- * libusb_alloc_transfer() with an appropriate number of isochronous packets.
-- *
-- * During filling, set \ref libusb_transfer::type "type" to
-- * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
-- * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
-- * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
-- * or equal to the number of packets you requested during allocation.
-- * libusb_alloc_transfer() does not set either of these fields for you, given
-- * that you might not even use the transfer on an isochronous endpoint.
-- *
-- * Next, populate the length field for the first num_iso_packets entries in
-- * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
-- * 5.6.3 of the USB2 specifications describe how the maximum isochronous
-- * packet length is determined by the wMaxPacketSize field in the endpoint
-- * descriptor.
-- * Two functions can help you here:
-- *
-- * - libusb_get_max_iso_packet_size() is an easy way to determine the max
-- *   packet size for an isochronous endpoint. Note that the maximum packet
-- *   size is actually the maximum number of bytes that can be transmitted in
-- *   a single microframe, therefore this function multiplies the maximum number
-- *   of bytes per transaction by the number of transaction opportunities per
-- *   microframe.
-- * - libusb_set_iso_packet_lengths() assigns the same length to all packets
-- *   within a transfer, which is usually what you want.
-- *
-- * For outgoing transfers, you'll obviously fill the buffer and populate the
-- * packet descriptors in hope that all the data gets transferred. For incoming
-- * transfers, you must ensure the buffer has sufficient capacity for
-- * the situation where all packets transfer the full amount of requested data.
-- *
-- * Completion handling requires some extra consideration. The
-- * \ref libusb_transfer::actual_length "actual_length" field of the transfer
-- * is meaningless and should not be examined; instead you must refer to the
-- * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
-- * each individual packet.
-- *
-- * The \ref libusb_transfer::status "status" field of the transfer is also a
-- * little misleading:
-- *  - If the packets were submitted and the isochronous data microframes
-- *    completed normally, status will have value
-- *    \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
-- *    "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
-- *    delays are not counted as transfer errors; the transfer.status field may
-- *    indicate COMPLETED even if some or all of the packets failed. Refer to
-- *    the \ref libusb_iso_packet_descriptor::status "status" field of each
-- *    individual packet to determine packet failures.
-- *  - The status field will have value
-- *    \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
-- *    "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
-- *  - Other transfer status codes occur with normal behaviour.
-- *
-- * The data for each packet will be found at an offset into the buffer that
-- * can be calculated as if each prior packet completed in full. The
-- * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
-- * functions may help you here.
-- *
-  * <b>Note</b>: Some operating systems (e.g. Linux) may impose limits on the
-  * length of individual isochronous packets and/or the total length of the
-  * isochronous transfer. Such limits can be difficult for libusb to detect,
-  * so the library will simply try and submit the transfer as set up by you.
-  * If the transfer fails to submit because it is too large,
 - * \section asynclimits Transfer length limitations
 - *
 - * Some operating systems may impose limits on the length of the transfer data
 - * buffer or, in the case of isochronous transfers, the length of individual
 - * isochronous packets. Such limits can be difficult for libusb to detect, so
 - * in most cases the library will simply try and submit the transfer as set up
 - * by you. If the transfer fails to submit because it is too large,
-- * libusb_submit_transfer() will return
-- * \ref libusb_error::LIBUSB_ERROR_INVALID_PARAM "LIBUSB_ERROR_INVALID_PARAM".
 - *
 - * The following are known limits for control transfer lengths. Note that this
 - * length includes the 8-byte setup packet.
 - * - Linux (4,096 bytes)
 - * - Windows (4,096 bytes)
-- *
-- * \section asyncmem Memory caveats
-- *
-- * In most circumstances, it is not safe to use stack memory for transfer
-- * buffers. This is because the function that fired off the asynchronous
-- * transfer may return before libusb has finished using the buffer, and when
-- * the function returns it's stack gets destroyed. This is true for both
-- * host-to-device and device-to-host transfers.
-- *
-- * The only case in which it is safe to use stack memory is where you can
-- * guarantee that the function owning the stack space for the buffer does not
-- * return until after the transfer's callback function has completed. In every
-- * other case, you need to use heap memory instead.
-- *
-- * \section asyncflags Fine control
-- *
-- * Through using this asynchronous interface, you may find yourself repeating
-- * a few simple operations many times. You can apply a bitwise OR of certain
-- * flags to a transfer to simplify certain things:
-- * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
-- *   "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
-- *   less than the requested amount of data being marked with status
-- *   \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
-- *   (they would normally be regarded as COMPLETED)
-- * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
-- *   "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
-- *   buffer when freeing the transfer.
-- * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
-- *   "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
-- *   transfer after the transfer callback returns.
-- *
-- * \section asyncevent Event handling
-- *
-- * An asynchronous model requires that libusb perform work at various
-- * points in time - namely processing the results of previously-submitted
-- * transfers and invoking the user-supplied callback function.
-- *
-- * This gives rise to the libusb_handle_events() function which your
-- * application must call into when libusb has work do to. This gives libusb
-- * the opportunity to reap pending transfers, invoke callbacks, etc.
-- *
-  * There are 2 different approaches to dealing with libusb_handle_events:
 - * \note
 - * All event handling is performed by whichever thread calls the
 - * libusb_handle_events() function. libusb does not invoke any callbacks
 - * outside of this context. Consequently, any callbacks will be run on the
 - * thread that calls the libusb_handle_events() function.
 - *
 - * When to call the libusb_handle_events() function depends on which model
 - * your application decides to use. The 2 different approaches:
-- *
-- * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
-- *    thread.
-- * -# Integrate libusb with your application's main event loop. libusb
-- *    exposes a set of file descriptors which allow you to do this.
-- *
-- * The first approach has the big advantage that it will also work on Windows
-- * were libusb' poll API for select / poll integration is not available. So
-- * if you want to support Windows and use the async API, you must use this
-- * approach, see the \ref eventthread "Using an event handling thread" section
-- * below for details.
-- *
-- * If you prefer a single threaded approach with a single central event loop,
-- * see the \ref libusb_poll "polling and timing" section for how to integrate libusb
-- * into your application's main event loop.
-- *
-- * \section eventthread Using an event handling thread
-- *
-- * Lets begin with stating the obvious: If you're going to use a separate
-- * thread for libusb event handling, your callback functions MUST be
-  * threadsafe.
 - * thread-safe.
-- *
-- * Other then that doing event handling from a separate thread, is mostly
-- * simple. You can use an event thread function as follows:
--\code
--void *event_thread_func(void *ctx)
--{
--    while (event_thread_run)
--        libusb_handle_events(ctx);
--
--    return NULL;
--}
--\endcode
-- *
-- * There is one caveat though, stopping this thread requires setting the
-- * event_thread_run variable to 0, and after that libusb_handle_events() needs
-- * to return control to event_thread_func. But unless some event happens,
-- * libusb_handle_events() will not return.
-- *
-- * There are 2 different ways of dealing with this, depending on if your
-- * application uses libusb' \ref libusb_hotplug "hotplug" support or not.
-- *
-- * Applications which do not use hotplug support, should not start the event
-- * thread until after their first call to libusb_open(), and should stop the
-- * thread when closing the last open device as follows:
--\code
--void my_close_handle(libusb_device_handle *dev_handle)
--{
--    if (open_devs == 1)
--        event_thread_run = 0;
--
--    libusb_close(dev_handle); // This wakes up libusb_handle_events()
--
--    if (open_devs == 1)
--        pthread_join(event_thread);
--
--    open_devs--;
--}
--\endcode
-- *
-- * Applications using hotplug support should start the thread at program init,
-- * after having successfully called libusb_hotplug_register_callback(), and
-- * should stop the thread at program exit as follows:
--\code
--void my_libusb_exit(void)
--{
--    event_thread_run = 0;
--    libusb_hotplug_deregister_callback(ctx, hotplug_cb_handle); // This wakes up libusb_handle_events()
--    pthread_join(event_thread);
--    libusb_exit(ctx);
--}
--\endcode
-- */
--
--/**
-- * @defgroup libusb_poll Polling and timing
-- *
-- * This page documents libusb's functions for polling events and timing.
-- * These functions are only necessary for users of the
-- * \ref libusb_asyncio "asynchronous API". If you are only using the simpler
-- * \ref libusb_syncio "synchronous API" then you do not need to ever call these
-- * functions.
-- *
-- * The justification for the functionality described here has already been
-- * discussed in the \ref asyncevent "event handling" section of the
-- * asynchronous API documentation. In summary, libusb does not create internal
-- * threads for event processing and hence relies on your application calling
-- * into libusb at certain points in time so that pending events can be handled.
-- *
-- * Your main loop is probably already calling poll() or select() or a
-- * variant on a set of file descriptors for other event sources (e.g. keyboard
-- * button presses, mouse movements, network sockets, etc). You then add
-- * libusb's file descriptors to your poll()/select() calls, and when activity
-- * is detected on such descriptors you know it is time to call
-- * libusb_handle_events().
-- *
-- * There is one final event handling complication. libusb supports
-- * asynchronous transfers which time out after a specified time period.
-- *
-- * On some platforms a timerfd is used, so the timeout handling is just another
-- * fd, on other platforms this requires that libusb is called into at or after
-- * the timeout to handle it. So, in addition to considering libusb's file
-- * descriptors in your main event loop, you must also consider that libusb
-- * sometimes needs to be called into at fixed points in time even when there
-- * is no file descriptor activity, see \ref polltime details.
-- *
-- * In order to know precisely when libusb needs to be called into, libusb
-- * offers you a set of pollable file descriptors and information about when
-- * the next timeout expires.
-- *
-- * If you are using the asynchronous I/O API, you must take one of the two
-- * following options, otherwise your I/O will not complete.
-- *
-- * \section pollsimple The simple option
-- *
-- * If your application revolves solely around libusb and does not need to
-- * handle other event sources, you can have a program structure as follows:
--\code
--// initialize libusb
--// find and open device
--// maybe fire off some initial async I/O
--
--while (user_has_not_requested_exit)
--      libusb_handle_events(ctx);
--
--// clean up and exit
--\endcode
-- *
-- * With such a simple main loop, you do not have to worry about managing
-- * sets of file descriptors or handling timeouts. libusb_handle_events() will
-- * handle those details internally.
-- *
-- * \section libusb_pollmain The more advanced option
-- *
-- * \note This functionality is currently only available on Unix-like platforms.
-- * On Windows, libusb_get_pollfds() simply returns NULL. Applications which
-- * want to support Windows are advised to use an \ref eventthread
-- * "event handling thread" instead.
-- *
-- * In more advanced applications, you will already have a main loop which
-- * is monitoring other event sources: network sockets, X11 events, mouse
-- * movements, etc. Through exposing a set of file descriptors, libusb is
-- * designed to cleanly integrate into such main loops.
-- *
-- * In addition to polling file descriptors for the other event sources, you
-- * take a set of file descriptors from libusb and monitor those too. When you
-- * detect activity on libusb's file descriptors, you call
-- * libusb_handle_events_timeout() in non-blocking mode.
-- *
-- * What's more, libusb may also need to handle events at specific moments in
-- * time. No file descriptor activity is generated at these times, so your
-- * own application needs to be continually aware of when the next one of these
-- * moments occurs (through calling libusb_get_next_timeout()), and then it
-- * needs to call libusb_handle_events_timeout() in non-blocking mode when
-- * these moments occur. This means that you need to adjust your
-- * poll()/select() timeout accordingly.
-- *
-- * libusb provides you with a set of file descriptors to poll and expects you
-- * to poll all of them, treating them as a single entity. The meaning of each
-- * file descriptor in the set is an internal implementation detail,
-- * platform-dependent and may vary from release to release. Don't try and
-- * interpret the meaning of the file descriptors, just do as libusb indicates,
-- * polling all of them at once.
-- *
-- * In pseudo-code, you want something that looks like:
--\code
--// initialise libusb
--
--libusb_get_pollfds(ctx)
--while (user has not requested application exit) {
--      libusb_get_next_timeout(ctx);
--      poll(on libusb file descriptors plus any other event sources of interest,
--              using a timeout no larger than the value libusb just suggested)
--      if (poll() indicated activity on libusb file descriptors)
--              libusb_handle_events_timeout(ctx, &zero_tv);
--      if (time has elapsed to or beyond the libusb timeout)
--              libusb_handle_events_timeout(ctx, &zero_tv);
--      // handle events from other sources here
--}
--
--// clean up and exit
--\endcode
-- *
-- * \subsection polltime Notes on time-based events
-- *
-- * The above complication with having to track time and call into libusb at
-- * specific moments is a bit of a headache. For maximum compatibility, you do
-- * need to write your main loop as above, but you may decide that you can
-- * restrict the supported platforms of your application and get away with
-- * a more simplistic scheme.
-- *
-- * These time-based event complications are \b not required on the following
-- * platforms:
-- *  - Darwin
-- *  - Linux, provided that the following version requirements are satisfied:
-- *   - Linux v2.6.27 or newer, compiled with timerfd support
-- *   - glibc v2.9 or newer
-- *   - libusb v1.0.5 or newer
-- *
-- * Under these configurations, libusb_get_next_timeout() will \em always return
-- * 0, so your main loop can be simplified to:
--\code
--// initialise libusb
--
--libusb_get_pollfds(ctx)
--while (user has not requested application exit) {
--      poll(on libusb file descriptors plus any other event sources of interest,
--              using any timeout that you like)
--      if (poll() indicated activity on libusb file descriptors)
--              libusb_handle_events_timeout(ctx, &zero_tv);
--      // handle events from other sources here
--}
--
--// clean up and exit
--\endcode
-- *
-- * Do remember that if you simplify your main loop to the above, you will
-- * lose compatibility with some platforms (including legacy Linux platforms,
-- * and <em>any future platforms supported by libusb which may have time-based
-- * event requirements</em>). The resultant problems will likely appear as
-- * strange bugs in your application.
-- *
-- * You can use the libusb_pollfds_handle_timeouts() function to do a runtime
-- * check to see if it is safe to ignore the time-based event complications.
-- * If your application has taken the shortcut of ignoring libusb's next timeout
-- * in your main loop, then you are advised to check the return value of
-- * libusb_pollfds_handle_timeouts() during application startup, and to abort
-- * if the platform does suffer from these timing complications.
-- *
-- * \subsection fdsetchange Changes in the file descriptor set
-- *
-- * The set of file descriptors that libusb uses as event sources may change
-- * during the life of your application. Rather than having to repeatedly
-- * call libusb_get_pollfds(), you can set up notification functions for when
-- * the file descriptor set changes using libusb_set_pollfd_notifiers().
-- *
-- * \subsection mtissues Multi-threaded considerations
-- *
-- * Unfortunately, the situation is complicated further when multiple threads
-- * come into play. If two threads are monitoring the same file descriptors,
-- * the fact that only one thread will be woken up when an event occurs causes
-- * some headaches.
-- *
-- * The events lock, event waiters lock, and libusb_handle_events_locked()
-- * entities are added to solve these problems. You do not need to be concerned
-- * with these entities otherwise.
-- *
-- * See the extra documentation: \ref libusb_mtasync
-- */
--
--/** \page libusb_mtasync Multi-threaded applications and asynchronous I/O
-- *
-- * libusb is a thread-safe library, but extra considerations must be applied
-- * to applications which interact with libusb from multiple threads.
-- *
-- * The underlying issue that must be addressed is that all libusb I/O
-- * revolves around monitoring file descriptors through the poll()/select()
-- * system calls. This is directly exposed at the
-- * \ref libusb_asyncio "asynchronous interface" but it is important to note that the
-- * \ref libusb_syncio "synchronous interface" is implemented on top of the
-  * asynchonrous interface, therefore the same considerations apply.
 - * asynchronous interface, therefore the same considerations apply.
-- *
-- * The issue is that if two or more threads are concurrently calling poll()
-- * or select() on libusb's file descriptors then only one of those threads
-- * will be woken up when an event arrives. The others will be completely
-- * oblivious that anything has happened.
-- *
-- * Consider the following pseudo-code, which submits an asynchronous transfer
-- * then waits for its completion. This style is one way you could implement a
-- * synchronous interface on top of the asynchronous interface (and libusb
-- * does something similar, albeit more advanced due to the complications
-- * explained on this page).
-- *
--\code
--void cb(struct libusb_transfer *transfer)
--{
--      int *completed = transfer->user_data;
--      *completed = 1;
--}
--
--void myfunc() {
--      struct libusb_transfer *transfer;
--      unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE] __attribute__ ((aligned (2)));
--      int completed = 0;
--
--      transfer = libusb_alloc_transfer(0);
--      libusb_fill_control_setup(buffer,
--              LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
--      libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
--      libusb_submit_transfer(transfer);
--
--      while (!completed) {
--              poll(libusb file descriptors, 120*1000);
--              if (poll indicates activity)
--                      libusb_handle_events_timeout(ctx, &zero_tv);
--      }
--      printf("completed!");
--      // other code here
--}
--\endcode
-- *
-- * Here we are <em>serializing</em> completion of an asynchronous event
-- * against a condition - the condition being completion of a specific transfer.
-- * The poll() loop has a long timeout to minimize CPU usage during situations
-- * when nothing is happening (it could reasonably be unlimited).
-- *
-- * If this is the only thread that is polling libusb's file descriptors, there
-- * is no problem: there is no danger that another thread will swallow up the
-- * event that we are interested in. On the other hand, if there is another
-- * thread polling the same descriptors, there is a chance that it will receive
-- * the event that we were interested in. In this situation, <tt>myfunc()</tt>
-- * will only realise that the transfer has completed on the next iteration of
-- * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is
-- * undesirable, and don't even think about using short timeouts to circumvent
-- * this issue!
-- *
-- * The solution here is to ensure that no two threads are ever polling the
-- * file descriptors at the same time. A naive implementation of this would
-- * impact the capabilities of the library, so libusb offers the scheme
-- * documented below to ensure no loss of functionality.
-- *
-- * Before we go any further, it is worth mentioning that all libusb-wrapped
-- * event handling procedures fully adhere to the scheme documented below.
-- * This includes libusb_handle_events() and its variants, and all the
-- * synchronous I/O functions - libusb hides this headache from you.
-- *
-- * \section Using libusb_handle_events() from multiple threads
-- *
-- * Even when only using libusb_handle_events() and synchronous I/O functions,
-- * you can still have a race condition. You might be tempted to solve the
-- * above with libusb_handle_events() like so:
-- *
--\code
--      libusb_submit_transfer(transfer);
--
--      while (!completed) {
--              libusb_handle_events(ctx);
--      }
--      printf("completed!");
--\endcode
-- *
-- * This however has a race between the checking of completed and
-- * libusb_handle_events() acquiring the events lock, so another thread
-- * could have completed the transfer, resulting in this thread hanging
-- * until either a timeout or another event occurs. See also commit
-- * 6696512aade99bb15d6792af90ae329af270eba6 which fixes this in the
-- * synchronous API implementation of libusb.
-- *
-- * Fixing this race requires checking the variable completed only after
-- * taking the event lock, which defeats the concept of just calling
-- * libusb_handle_events() without worrying about locking. This is why
-- * libusb-1.0.9 introduces the new libusb_handle_events_timeout_completed()
-- * and libusb_handle_events_completed() functions, which handles doing the
-- * completion check for you after they have acquired the lock:
-- *
--\code
--      libusb_submit_transfer(transfer);
--
--      while (!completed) {
--              libusb_handle_events_completed(ctx, &completed);
--      }
--      printf("completed!");
--\endcode
-- *
-- * This nicely fixes the race in our example. Note that if all you want to
-- * do is submit a single transfer and wait for its completion, then using
-- * one of the synchronous I/O functions is much easier.
 - *
 - * \note
 - * The `completed` variable must be modified while holding the event lock,
 - * otherwise a race condition can still exist. It is simplest to do so from
 - * within the transfer callback as shown above.
-- *
-- * \section eventlock The events lock
-- *
-- * The problem is when we consider the fact that libusb exposes file
-- * descriptors to allow for you to integrate asynchronous USB I/O into
-- * existing main loops, effectively allowing you to do some work behind
-- * libusb's back. If you do take libusb's file descriptors and pass them to
-- * poll()/select() yourself, you need to be aware of the associated issues.
-- *
-- * The first concept to be introduced is the events lock. The events lock
-- * is used to serialize threads that want to handle events, such that only
-- * one thread is handling events at any one time.
-- *
-- * You must take the events lock before polling libusb file descriptors,
-- * using libusb_lock_events(). You must release the lock as soon as you have
-- * aborted your poll()/select() loop, using libusb_unlock_events().
-- *
-- * \section threadwait Letting other threads do the work for you
-- *
-- * Although the events lock is a critical part of the solution, it is not
-- * enough on it's own. You might wonder if the following is sufficient...
--\code
--      libusb_lock_events(ctx);
--      while (!completed) {
--              poll(libusb file descriptors, 120*1000);
--              if (poll indicates activity)
--                      libusb_handle_events_timeout(ctx, &zero_tv);
--      }
--      libusb_unlock_events(ctx);
--\endcode
-- * ...and the answer is that it is not. This is because the transfer in the
-- * code shown above may take a long time (say 30 seconds) to complete, and
-- * the lock is not released until the transfer is completed.
-- *
-- * Another thread with similar code that wants to do event handling may be
-- * working with a transfer that completes after a few milliseconds. Despite
-- * having such a quick completion time, the other thread cannot check that
-- * status of its transfer until the code above has finished (30 seconds later)
-- * due to contention on the lock.
-- *
-- * To solve this, libusb offers you a mechanism to determine when another
-- * thread is handling events. It also offers a mechanism to block your thread
-- * until the event handling thread has completed an event (and this mechanism
-- * does not involve polling of file descriptors).
-- *
-- * After determining that another thread is currently handling events, you
-- * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters().
-- * You then re-check that some other thread is still handling events, and if
-- * so, you call libusb_wait_for_event().
-- *
-- * libusb_wait_for_event() puts your application to sleep until an event
-- * occurs, or until a thread releases the events lock. When either of these
-- * things happen, your thread is woken up, and should re-check the condition
-- * it was waiting on. It should also re-check that another thread is handling
-- * events, and if not, it should start handling events itself.
-- *
-- * This looks like the following, as pseudo-code:
--\code
--retry:
--if (libusb_try_lock_events(ctx) == 0) {
--      // we obtained the event lock: do our own event handling
--      while (!completed) {
--              if (!libusb_event_handling_ok(ctx)) {
--                      libusb_unlock_events(ctx);
--                      goto retry;
--              }
--              poll(libusb file descriptors, 120*1000);
--              if (poll indicates activity)
--                      libusb_handle_events_locked(ctx, 0);
--      }
--      libusb_unlock_events(ctx);
--} else {
--      // another thread is doing event handling. wait for it to signal us that
--      // an event has completed
--      libusb_lock_event_waiters(ctx);
--
--      while (!completed) {
--              // now that we have the event waiters lock, double check that another
--              // thread is still handling events for us. (it may have ceased handling
--              // events in the time it took us to reach this point)
--              if (!libusb_event_handler_active(ctx)) {
--                      // whoever was handling events is no longer doing so, try again
--                      libusb_unlock_event_waiters(ctx);
--                      goto retry;
--              }
--
--              libusb_wait_for_event(ctx, NULL);
--      }
--      libusb_unlock_event_waiters(ctx);
--}
--printf("completed!\n");
--\endcode
-- *
-- * A naive look at the above code may suggest that this can only support
-- * one event waiter (hence a total of 2 competing threads, the other doing
-- * event handling), because the event waiter seems to have taken the event
-- * waiters lock while waiting for an event. However, the system does support
-- * multiple event waiters, because libusb_wait_for_event() actually drops
-  * the lock while waiting, and reaquires it before continuing.
 - * the lock while waiting, and reacquires it before continuing.
-- *
-- * We have now implemented code which can dynamically handle situations where
-- * nobody is handling events (so we should do it ourselves), and it can also
-- * handle situations where another thread is doing event handling (so we can
-- * piggyback onto them). It is also equipped to handle a combination of
-- * the two, for example, another thread is doing event handling, but for
-- * whatever reason it stops doing so before our condition is met, so we take
-- * over the event handling.
-- *
-- * Four functions were introduced in the above pseudo-code. Their importance
-- * should be apparent from the code shown above.
-- * -# libusb_try_lock_events() is a non-blocking function which attempts
-- *    to acquire the events lock but returns a failure code if it is contended.
-- * -# libusb_event_handling_ok() checks that libusb is still happy for your
-- *    thread to be performing event handling. Sometimes, libusb needs to
-- *    interrupt the event handler, and this is how you can check if you have
-- *    been interrupted. If this function returns 0, the correct behaviour is
-- *    for you to give up the event handling lock, and then to repeat the cycle.
-- *    The following libusb_try_lock_events() will fail, so you will become an
-- *    events waiter. For more information on this, read \ref fullstory below.
-- * -# libusb_handle_events_locked() is a variant of
-- *    libusb_handle_events_timeout() that you can call while holding the
-- *    events lock. libusb_handle_events_timeout() itself implements similar
-- *    logic to the above, so be sure not to call it when you are
-- *    "working behind libusb's back", as is the case here.
-- * -# libusb_event_handler_active() determines if someone is currently
-- *    holding the events lock
-- *
-- * You might be wondering why there is no function to wake up all threads
-- * blocked on libusb_wait_for_event(). This is because libusb can do this
-- * internally: it will wake up all such threads when someone calls
-- * libusb_unlock_events() or when a transfer completes (at the point after its
-- * callback has returned).
-- *
-- * \subsection fullstory The full story
-- *
-- * The above explanation should be enough to get you going, but if you're
-- * really thinking through the issues then you may be left with some more
-- * questions regarding libusb's internals. If you're curious, read on, and if
-- * not, skip to the next section to avoid confusing yourself!
-- *
-- * The immediate question that may spring to mind is: what if one thread
-- * modifies the set of file descriptors that need to be polled while another
-- * thread is doing event handling?
-- *
-- * There are 2 situations in which this may happen.
-- * -# libusb_open() will add another file descriptor to the poll set,
-- *    therefore it is desirable to interrupt the event handler so that it
-- *    restarts, picking up the new descriptor.
-- * -# libusb_close() will remove a file descriptor from the poll set. There
-- *    are all kinds of race conditions that could arise here, so it is
-- *    important that nobody is doing event handling at this time.
-- *
-- * libusb handles these issues internally, so application developers do not
-- * have to stop their event handlers while opening/closing devices. Here's how
-- * it works, focusing on the libusb_close() situation first:
-- *
-- * -# During initialization, libusb opens an internal pipe, and it adds the read
-- *    end of this pipe to the set of file descriptors to be polled.
-- * -# During libusb_close(), libusb writes some dummy data on this event pipe.
-- *    This immediately interrupts the event handler. libusb also records
-- *    internally that it is trying to interrupt event handlers for this
-- *    high-priority event.
-- * -# At this point, some of the functions described above start behaving
-- *    differently:
-- *   - libusb_event_handling_ok() starts returning 1, indicating that it is NOT
-- *     OK for event handling to continue.
-- *   - libusb_try_lock_events() starts returning 1, indicating that another
-- *     thread holds the event handling lock, even if the lock is uncontended.
-- *   - libusb_event_handler_active() starts returning 1, indicating that
-- *     another thread is doing event handling, even if that is not true.
-- * -# The above changes in behaviour result in the event handler stopping and
-- *    giving up the events lock very quickly, giving the high-priority
-- *    libusb_close() operation a "free ride" to acquire the events lock. All
-- *    threads that are competing to do event handling become event waiters.
-- * -# With the events lock held inside libusb_close(), libusb can safely remove
-- *    a file descriptor from the poll set, in the safety of knowledge that
-- *    nobody is polling those descriptors or trying to access the poll set.
-- * -# After obtaining the events lock, the close operation completes very
-- *    quickly (usually a matter of milliseconds) and then immediately releases
-- *    the events lock.
-- * -# At the same time, the behaviour of libusb_event_handling_ok() and friends
-- *    reverts to the original, documented behaviour.
-- * -# The release of the events lock causes the threads that are waiting for
-- *    events to be woken up and to start competing to become event handlers
-- *    again. One of them will succeed; it will then re-obtain the list of poll
-- *    descriptors, and USB I/O will then continue as normal.
-- *
-- * libusb_open() is similar, and is actually a more simplistic case. Upon a
-- * call to libusb_open():
-- *
-- * -# The device is opened and a file descriptor is added to the poll set.
-- * -# libusb sends some dummy data on the event pipe, and records that it
-- *    is trying to modify the poll descriptor set.
-- * -# The event handler is interrupted, and the same behaviour change as for
-- *    libusb_close() takes effect, causing all event handling threads to become
-- *    event waiters.
-- * -# The libusb_open() implementation takes its free ride to the events lock.
-- * -# Happy that it has successfully paused the events handler, libusb_open()
-- *    releases the events lock.
-- * -# The event waiter threads are all woken up and compete to become event
-- *    handlers again. The one that succeeds will obtain the list of poll
-- *    descriptors again, which will include the addition of the new device.
-- *
-- * \subsection concl Closing remarks
-- *
-- * The above may seem a little complicated, but hopefully I have made it clear
-- * why such complications are necessary. Also, do not forget that this only
-- * applies to applications that take libusb's file descriptors and integrate
-- * them into their own polling loops.
-- *
-- * You may decide that it is OK for your multi-threaded application to ignore
-- * some of the rules and locks detailed above, because you don't think that
-- * two threads can ever be polling the descriptors at the same time. If that
-- * is the case, then that's good news for you because you don't have to worry.
-- * But be careful here; remember that the synchronous I/O functions do event
-- * handling internally. If you have one thread doing event handling in a loop
-- * (without implementing the rules and locking semantics documented above)
-- * and another trying to send a synchronous USB transfer, you will end up with
-- * two threads monitoring the same descriptors, and the above-described
-- * undesirable behaviour occurring. The solution is for your polling thread to
-- * play by the rules; the synchronous I/O functions do so, and this will result
-- * in them getting along in perfect harmony.
-- *
-- * If you do have a dedicated thread doing event handling, it is perfectly
-- * legal for it to take the event handling lock for long periods of time. Any
-- * synchronous I/O functions you call from other threads will transparently
-- * fall back to the "event waiters" mechanism detailed above. The only
-- * consideration that your event handling thread must apply is the one related
-- * to libusb_event_handling_ok(): you must call this before every poll(), and
-- * give up the events lock if instructed.
-- */
--
--int usbi_io_init(struct libusb_context *ctx)
--{
--      int r;
--
--      usbi_mutex_init(&ctx->flying_transfers_lock);
--      usbi_mutex_init(&ctx->events_lock);
--      usbi_mutex_init(&ctx->event_waiters_lock);
--      usbi_cond_init(&ctx->event_waiters_cond);
--      usbi_mutex_init(&ctx->event_data_lock);
--      usbi_tls_key_create(&ctx->event_handling_key);
--      list_init(&ctx->flying_transfers);
-       list_init(&ctx->ipollfds);
 -      list_init(&ctx->event_sources);
 -      list_init(&ctx->removed_event_sources);
--      list_init(&ctx->hotplug_msgs);
--      list_init(&ctx->completed_transfers);
--
-       /* FIXME should use an eventfd on kernels that support it */
-       r = usbi_pipe(ctx->event_pipe);
-       if (r < 0) {
-               r = LIBUSB_ERROR_OTHER;
 -      r = usbi_create_event(&ctx->event);
 -      if (r < 0)
--              goto err;
-       }
--
-       r = usbi_add_pollfd(ctx, ctx->event_pipe[0], POLLIN);
 -      r = usbi_add_event_source(ctx, USBI_EVENT_OS_HANDLE(&ctx->event), USBI_EVENT_POLL_EVENTS);
--      if (r < 0)
-               goto err_close_pipe;
 -              goto err_destroy_event;
--
- #ifdef USBI_TIMERFD_AVAILABLE
-       ctx->timerfd = timerfd_create(usbi_backend.get_timerfd_clockid(),
-               TFD_NONBLOCK | TFD_CLOEXEC);
-       if (ctx->timerfd >= 0) {
-               usbi_dbg("using timerfd for timeouts");
-               r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN);
 -#ifdef HAVE_OS_TIMER
 -      r = usbi_create_timer(&ctx->timer);
 -      if (r == 0) {
 -              usbi_dbg("using timer for timeouts");
 -              r = usbi_add_event_source(ctx, USBI_TIMER_OS_HANDLE(&ctx->timer), USBI_TIMER_POLL_EVENTS);
--              if (r < 0)
-                       goto err_close_timerfd;
 -                      goto err_destroy_timer;
--      } else {
-               usbi_dbg("timerfd not available (code %d error %d)", ctx->timerfd, errno);
-               ctx->timerfd = -1;
 -              usbi_dbg("timer not available for timeouts");
--      }
--#endif
--
--      return 0;
--
- #ifdef USBI_TIMERFD_AVAILABLE
- err_close_timerfd:
-       close(ctx->timerfd);
-       usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
 -#ifdef HAVE_OS_TIMER
 -err_destroy_timer:
 -      usbi_destroy_timer(&ctx->timer);
 -      usbi_remove_event_source(ctx, USBI_EVENT_OS_HANDLE(&ctx->event));
--#endif
- err_close_pipe:
-       usbi_close(ctx->event_pipe[0]);
-       usbi_close(ctx->event_pipe[1]);
 -err_destroy_event:
 -      usbi_destroy_event(&ctx->event);
--err:
--      usbi_mutex_destroy(&ctx->flying_transfers_lock);
--      usbi_mutex_destroy(&ctx->events_lock);
--      usbi_mutex_destroy(&ctx->event_waiters_lock);
--      usbi_cond_destroy(&ctx->event_waiters_cond);
--      usbi_mutex_destroy(&ctx->event_data_lock);
--      usbi_tls_key_delete(ctx->event_handling_key);
--      return r;
 -}
 -
 -static void cleanup_removed_event_sources(struct libusb_context *ctx)
 -{
 -      struct usbi_event_source *ievent_source, *tmp;
 -
 -      for_each_removed_event_source_safe(ctx, ievent_source, tmp) {
 -              list_del(&ievent_source->list);
 -              free(ievent_source);
 -      }
--}
--
--void usbi_io_exit(struct libusb_context *ctx)
--{
-       usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
-       usbi_close(ctx->event_pipe[0]);
-       usbi_close(ctx->event_pipe[1]);
- #ifdef USBI_TIMERFD_AVAILABLE
-       if (usbi_using_timerfd(ctx)) {
-               usbi_remove_pollfd(ctx, ctx->timerfd);
-               close(ctx->timerfd);
 -#ifdef HAVE_OS_TIMER
 -      if (usbi_using_timer(ctx)) {
 -              usbi_remove_event_source(ctx, USBI_TIMER_OS_HANDLE(&ctx->timer));
 -              usbi_destroy_timer(&ctx->timer);
--      }
--#endif
 -      usbi_remove_event_source(ctx, USBI_EVENT_OS_HANDLE(&ctx->event));
 -      usbi_destroy_event(&ctx->event);
--      usbi_mutex_destroy(&ctx->flying_transfers_lock);
--      usbi_mutex_destroy(&ctx->events_lock);
--      usbi_mutex_destroy(&ctx->event_waiters_lock);
--      usbi_cond_destroy(&ctx->event_waiters_cond);
--      usbi_mutex_destroy(&ctx->event_data_lock);
--      usbi_tls_key_delete(ctx->event_handling_key);
-       if (ctx->pollfds)
-               free(ctx->pollfds);
 -      cleanup_removed_event_sources(ctx);
 -      free(ctx->event_data);
--}
--
- static int calculate_timeout(struct usbi_transfer *transfer)
 -static void calculate_timeout(struct usbi_transfer *itransfer)
--{
-       int r;
-       struct timespec current_time;
--      unsigned int timeout =
-               USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
 -              USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->timeout;
--
--      if (!timeout) {
-               timerclear(&transfer->timeout);
-               return 0;
-       }
-       r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, &current_time);
-       if (r < 0) {
-               usbi_err(ITRANSFER_CTX(transfer),
-                       "failed to read monotonic clock, errno=%d", errno);
-               return r;
 -              TIMESPEC_CLEAR(&itransfer->timeout);
 -              return;
--      }
--
-       current_time.tv_sec += timeout / 1000;
-       current_time.tv_nsec += (timeout % 1000) * 1000000;
 -      usbi_get_monotonic_time(&itransfer->timeout);
--
-       while (current_time.tv_nsec >= 1000000000) {
-               current_time.tv_nsec -= 1000000000;
-               current_time.tv_sec++;
 -      itransfer->timeout.tv_sec += timeout / 1000U;
 -      itransfer->timeout.tv_nsec += (timeout % 1000U) * 1000000L;
 -      if (itransfer->timeout.tv_nsec >= NSEC_PER_SEC) {
 -              ++itransfer->timeout.tv_sec;
 -              itransfer->timeout.tv_nsec -= NSEC_PER_SEC;
--      }
-       TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);
-       return 0;
--}
--
--/** \ingroup libusb_asyncio
-- * Allocate a libusb transfer with a specified number of isochronous packet
-- * descriptors. The returned transfer is pre-initialized for you. When the new
-- * transfer is no longer needed, it should be freed with
-- * libusb_free_transfer().
-- *
-- * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
-- * interrupt) should specify an iso_packets count of zero.
-- *
-- * For transfers intended for isochronous endpoints, specify an appropriate
-- * number of packet descriptors to be allocated as part of the transfer.
-- * The returned transfer is not specially initialized for isochronous I/O;
-- * you are still required to set the
-- * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
-- * \ref libusb_transfer::type "type" fields accordingly.
-- *
-- * It is safe to allocate a transfer with some isochronous packets and then
-- * use it on a non-isochronous endpoint. If you do this, ensure that at time
-- * of submission, num_iso_packets is 0 and that type is set appropriately.
-- *
-  * \param iso_packets number of isochronous packet descriptors to allocate
 - * \param iso_packets number of isochronous packet descriptors to allocate. Must be non-negative.
-- * \returns a newly allocated transfer, or NULL on error
-- */
--DEFAULT_VISIBILITY
--struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(
--      int iso_packets)
--{
 -      size_t priv_size;
 -      size_t alloc_size;
 -      unsigned char *ptr;
 -      struct usbi_transfer *itransfer;
--      struct libusb_transfer *transfer;
-       size_t os_alloc_size = usbi_backend.transfer_priv_size;
-       size_t alloc_size = sizeof(struct usbi_transfer)
 -
 -      assert(iso_packets >= 0);
 -      if (iso_packets < 0)
 -              return NULL;
 -
 -      priv_size = PTR_ALIGN(usbi_backend.transfer_priv_size);
 -      alloc_size = priv_size
 -              + sizeof(struct usbi_transfer)
--              + sizeof(struct libusb_transfer)
-               + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
-               + os_alloc_size;
-       struct usbi_transfer *itransfer = calloc(1, alloc_size);
-       if (!itransfer)
 -              + (sizeof(struct libusb_iso_packet_descriptor) * (size_t)iso_packets);
 -      ptr = calloc(1, alloc_size);
 -      if (!ptr)
--              return NULL;
--
 -      itransfer = (struct usbi_transfer *)(ptr + priv_size);
--      itransfer->num_iso_packets = iso_packets;
 -      itransfer->priv = ptr;
--      usbi_mutex_init(&itransfer->lock);
--      transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--      usbi_dbg("transfer %p", transfer);
--      return transfer;
--}
--
--/** \ingroup libusb_asyncio
-- * Free a transfer structure. This should be called for all transfers
-- * allocated with libusb_alloc_transfer().
-- *
-- * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
-- * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
-- * non-NULL, this function will also free the transfer buffer using the
-- * standard system memory allocator (e.g. free()).
-- *
-- * It is legal to call this function with a NULL transfer. In this case,
-- * the function will simply return safely.
-- *
-- * It is not legal to free an active transfer (one which has been submitted
-- * and has not yet completed).
-- *
-- * \param transfer the transfer to free
-- */
--void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
--{
--      struct usbi_transfer *itransfer;
 -      size_t priv_size;
 -      unsigned char *ptr;
 -
--      if (!transfer)
--              return;
--
--      usbi_dbg("transfer %p", transfer);
-       if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
 -      if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER)
--              free(transfer->buffer);
--
--      itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
--      usbi_mutex_destroy(&itransfer->lock);
-       free(itransfer);
- }
- #ifdef USBI_TIMERFD_AVAILABLE
- static int disarm_timerfd(struct libusb_context *ctx)
- {
-       const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
-       int r;
--
-       usbi_dbg("");
-       r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
-       if (r < 0)
-               return LIBUSB_ERROR_OTHER;
-       else
-               return 0;
 -      priv_size = PTR_ALIGN(usbi_backend.transfer_priv_size);
 -      ptr = (unsigned char *)itransfer - priv_size;
 -      assert(ptr == itransfer->priv);
 -      free(ptr);
--}
--
- /* iterates through the flying transfers, and rearms the timerfd based on the
 -/* iterates through the flying transfers, and rearms the timer based on the
-- * next upcoming timeout.
-- * must be called with flying_list locked.
-- * returns 0 on success or a LIBUSB_ERROR code on failure.
-- */
- static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
 -#ifdef HAVE_OS_TIMER
 -static int arm_timer_for_next_timeout(struct libusb_context *ctx)
--{
-       struct usbi_transfer *transfer;
 -      struct usbi_transfer *itransfer;
--
-       list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
-               struct timeval *cur_tv = &transfer->timeout;
 -      if (!usbi_using_timer(ctx))
 -              return 0;
 -
 -      for_each_transfer(ctx, itransfer) {
 -              struct timespec *cur_ts = &itransfer->timeout;
--
--              /* if we've reached transfers of infinite timeout, then we have no
--               * arming to do */
-               if (!timerisset(cur_tv))
-                       goto disarm;
 -              if (!TIMESPEC_IS_SET(cur_ts))
 -                      break;
--
--              /* act on first transfer that has not already been handled */
-               if (!(transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))) {
-                       int r;
-                       const struct itimerspec it = { {0, 0},
-                               { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
-                       usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
-                       r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
-                       if (r < 0)
-                               return LIBUSB_ERROR_OTHER;
-                       return 0;
 -              if (!(itransfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))) {
 -                      usbi_dbg("next timeout originally %ums", USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->timeout);
 -                      return usbi_arm_timer(&ctx->timer, cur_ts);
--              }
--      }
--
- disarm:
-       return disarm_timerfd(ctx);
 -      usbi_dbg("no timeouts, disarming timer");
 -      return usbi_disarm_timer(&ctx->timer);
--}
--#else
- static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
 -static inline int arm_timer_for_next_timeout(struct libusb_context *ctx)
--{
--      UNUSED(ctx);
--      return 0;
--}
--#endif
--
--/* add a transfer to the (timeout-sorted) active transfers list.
-- * This function will return non 0 if fails to update the timer,
-- * in which case the transfer is *not* on the flying_transfers list. */
- static int add_to_flying_list(struct usbi_transfer *transfer)
 -static int add_to_flying_list(struct usbi_transfer *itransfer)
--{
--      struct usbi_transfer *cur;
-       struct timeval *timeout = &transfer->timeout;
-       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
-       int r;
 -      struct timespec *timeout = &itransfer->timeout;
 -      struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
 -      int r = 0;
--      int first = 1;
--
-       r = calculate_timeout(transfer);
-       if (r)
-               return r;
 -      calculate_timeout(itransfer);
--
--      /* if we have no other flying transfers, start the list with this one */
--      if (list_empty(&ctx->flying_transfers)) {
-               list_add(&transfer->list, &ctx->flying_transfers);
 -              list_add(&itransfer->list, &ctx->flying_transfers);
--              goto out;
--      }
--
--      /* if we have infinite timeout, append to end of list */
-       if (!timerisset(timeout)) {
-               list_add_tail(&transfer->list, &ctx->flying_transfers);
 -      if (!TIMESPEC_IS_SET(timeout)) {
 -              list_add_tail(&itransfer->list, &ctx->flying_transfers);
--              /* first is irrelevant in this case */
--              goto out;
--      }
--
--      /* otherwise, find appropriate place in list */
-       list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
 -      for_each_transfer(ctx, cur) {
--              /* find first timeout that occurs after the transfer in question */
-               struct timeval *cur_tv = &cur->timeout;
 -              struct timespec *cur_ts = &cur->timeout;
--
-               if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
-                               (cur_tv->tv_sec == timeout->tv_sec &&
-                                       cur_tv->tv_usec > timeout->tv_usec)) {
-                       list_add_tail(&transfer->list, &cur->list);
 -              if (!TIMESPEC_IS_SET(cur_ts) || TIMESPEC_CMP(cur_ts, timeout, >)) {
 -                      list_add_tail(&itransfer->list, &cur->list);
--                      goto out;
--              }
--              first = 0;
--      }
--      /* first is 0 at this stage (list not empty) */
--
--      /* otherwise we need to be inserted at the end */
-       list_add_tail(&transfer->list, &ctx->flying_transfers);
 -      list_add_tail(&itransfer->list, &ctx->flying_transfers);
--out:
- #ifdef USBI_TIMERFD_AVAILABLE
-       if (first && usbi_using_timerfd(ctx) && timerisset(timeout)) {
 -#ifdef HAVE_OS_TIMER
 -      if (first && usbi_using_timer(ctx) && TIMESPEC_IS_SET(timeout)) {
--              /* if this transfer has the lowest timeout of all active transfers,
-                * rearm the timerfd with this transfer's timeout */
-               const struct itimerspec it = { {0, 0},
-                       { timeout->tv_sec, timeout->tv_usec * 1000 } };
-               usbi_dbg("arm timerfd for timeout in %dms (first in line)",
-                       USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
-               r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
-               if (r < 0) {
-                       usbi_warn(ctx, "failed to arm first timerfd (errno %d)", errno);
-                       r = LIBUSB_ERROR_OTHER;
-               }
 -               * rearm the timer with this transfer's timeout */
 -              usbi_dbg("arm timer for timeout in %ums (first in line)",
 -                      USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->timeout);
 -              r = usbi_arm_timer(&ctx->timer, timeout);
--      }
--#else
--      UNUSED(first);
--#endif
--
--      if (r)
-               list_del(&transfer->list);
 -              list_del(&itransfer->list);
--
--      return r;
--}
--
--/* remove a transfer from the active transfers list.
-- * This function will *always* remove the transfer from the
-- * flying_transfers list. It will return a LIBUSB_ERROR code
-- * if it fails to update the timer for the next timeout. */
- static int remove_from_flying_list(struct usbi_transfer *transfer)
 -static int remove_from_flying_list(struct usbi_transfer *itransfer)
--{
-       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
-       int rearm_timerfd;
 -      struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
 -      int rearm_timer;
--      int r = 0;
--
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
-       rearm_timerfd = (timerisset(&transfer->timeout) &&
-               list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == transfer);
-       list_del(&transfer->list);
-       if (usbi_using_timerfd(ctx) && rearm_timerfd)
-               r = arm_timerfd_for_next_timeout(ctx);
 -      rearm_timer = (TIMESPEC_IS_SET(&itransfer->timeout) &&
 -              list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == itransfer);
 -      list_del(&itransfer->list);
 -      if (rearm_timer)
 -              r = arm_timer_for_next_timeout(ctx);
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
--
--      return r;
--}
--
--/** \ingroup libusb_asyncio
-- * Submit a transfer. This function will fire off the USB transfer and then
-- * return immediately.
-- *
-- * \param transfer the transfer to submit
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted.
-- * \returns LIBUSB_ERROR_NOT_SUPPORTED if the transfer flags are not supported
-- * by the operating system.
-- * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
-  * the operating system and/or hardware can support
 - * the operating system and/or hardware can support (see \ref asynclimits)
-- * \returns another LIBUSB_ERROR code on other failure
-- */
--int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
--{
--      struct usbi_transfer *itransfer =
--              LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
--      struct libusb_context *ctx = TRANSFER_CTX(transfer);
--      int r;
--
--      usbi_dbg("transfer %p", transfer);
--
--      /*
--       * Important note on locking, this function takes / releases locks
--       * in the following order:
--       *  take flying_transfers_lock
--       *  take itransfer->lock
--       *  clear transfer
--       *  add to flying_transfers list
--       *  release flying_transfers_lock
--       *  submit transfer
--       *  release itransfer->lock
--       *  if submit failed:
--       *   take flying_transfers_lock
--       *   remove from flying_transfers list
--       *   release flying_transfers_lock
--       *
--       * Note that it takes locks in the order a-b and then releases them
--       * in the same order a-b. This is somewhat unusual but not wrong,
--       * release order is not important as long as *all* locks are released
--       * before re-acquiring any locks.
--       *
--       * This means that the ordering of first releasing itransfer->lock
--       * and then re-acquiring the flying_transfers_list on error is
--       * important and must not be changed!
--       *
--       * This is done this way because when we take both locks we must always
--       * take flying_transfers_lock first to avoid ab-ba style deadlocks with
--       * the timeout handling and usbi_handle_disconnect paths.
--       *
--       * And we cannot release itransfer->lock before the submission is
--       * complete otherwise timeout handling for transfers with short
--       * timeouts may run before submission.
--       */
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
--      usbi_mutex_lock(&itransfer->lock);
--      if (itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT) {
--              usbi_mutex_unlock(&ctx->flying_transfers_lock);
--              usbi_mutex_unlock(&itransfer->lock);
--              return LIBUSB_ERROR_BUSY;
--      }
--      itransfer->transferred = 0;
--      itransfer->state_flags = 0;
--      itransfer->timeout_flags = 0;
--      r = add_to_flying_list(itransfer);
--      if (r) {
--              usbi_mutex_unlock(&ctx->flying_transfers_lock);
--              usbi_mutex_unlock(&itransfer->lock);
--              return r;
--      }
--      /*
--       * We must release the flying transfers lock here, because with
--       * some backends the submit_transfer method is synchroneous.
--       */
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
--
--      r = usbi_backend.submit_transfer(itransfer);
--      if (r == LIBUSB_SUCCESS) {
--              itransfer->state_flags |= USBI_TRANSFER_IN_FLIGHT;
--              /* keep a reference to this device */
--              libusb_ref_device(transfer->dev_handle->dev);
--      }
--      usbi_mutex_unlock(&itransfer->lock);
--
--      if (r != LIBUSB_SUCCESS)
--              remove_from_flying_list(itransfer);
--
--      return r;
--}
--
--/** \ingroup libusb_asyncio
-- * Asynchronously cancel a previously submitted transfer.
-- * This function returns immediately, but this does not indicate cancellation
-- * is complete. Your callback function will be invoked at some later time
-- * with a transfer status of
-- * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
-- * "LIBUSB_TRANSFER_CANCELLED."
-- *
-- * \param transfer the transfer to cancel
-- * \returns 0 on success
-- * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is not in progress,
-- * already complete, or already cancelled.
-- * \returns a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
--{
--      struct usbi_transfer *itransfer =
--              LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
--      int r;
--
--      usbi_dbg("transfer %p", transfer );
--      usbi_mutex_lock(&itransfer->lock);
--      if (!(itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT)
--                      || (itransfer->state_flags & USBI_TRANSFER_CANCELLING)) {
--              r = LIBUSB_ERROR_NOT_FOUND;
--              goto out;
--      }
--      r = usbi_backend.cancel_transfer(itransfer);
--      if (r < 0) {
--              if (r != LIBUSB_ERROR_NOT_FOUND &&
--                  r != LIBUSB_ERROR_NO_DEVICE)
--                      usbi_err(TRANSFER_CTX(transfer),
--                              "cancel transfer failed error %d", r);
--              else
--                      usbi_dbg("cancel transfer failed error %d", r);
--
--              if (r == LIBUSB_ERROR_NO_DEVICE)
--                      itransfer->state_flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
--      }
--
--      itransfer->state_flags |= USBI_TRANSFER_CANCELLING;
--
--out:
--      usbi_mutex_unlock(&itransfer->lock);
--      return r;
--}
--
--/** \ingroup libusb_asyncio
-- * Set a transfers bulk stream id. Note users are advised to use
-- * libusb_fill_bulk_stream_transfer() instead of calling this function
-- * directly.
-- *
-- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
-- *
-- * \param transfer the transfer to set the stream id for
-- * \param stream_id the stream id to set
-- * \see libusb_alloc_streams()
-- */
--void API_EXPORTED libusb_transfer_set_stream_id(
--      struct libusb_transfer *transfer, uint32_t stream_id)
--{
--      struct usbi_transfer *itransfer =
--              LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
--
--      itransfer->stream_id = stream_id;
--}
--
--/** \ingroup libusb_asyncio
-- * Get a transfers bulk stream id.
-- *
-- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
-- *
-- * \param transfer the transfer to get the stream id for
-- * \returns the stream id for the transfer
-- */
--uint32_t API_EXPORTED libusb_transfer_get_stream_id(
--      struct libusb_transfer *transfer)
--{
--      struct usbi_transfer *itransfer =
--              LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
--
--      return itransfer->stream_id;
--}
--
--/* Handle completion of a transfer (completion might be an error condition).
-- * This will invoke the user-supplied callback function, which may end up
-- * freeing the transfer. Therefore you cannot use the transfer structure
-- * after calling this function, and you should free all backend-specific
-- * data before calling it.
-- * Do not call this function with the usbi_transfer lock held. User-specified
-- * callback functions may attempt to directly resubmit the transfer, which
-- * will attempt to take the lock. */
--int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
--      enum libusb_transfer_status status)
--{
--      struct libusb_transfer *transfer =
--              USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--      struct libusb_device_handle *dev_handle = transfer->dev_handle;
--      uint8_t flags;
--      int r;
--
--      r = remove_from_flying_list(itransfer);
--      if (r < 0)
-               usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout, errno=%d", errno);
 -              usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout");
--
--      usbi_mutex_lock(&itransfer->lock);
--      itransfer->state_flags &= ~USBI_TRANSFER_IN_FLIGHT;
--      usbi_mutex_unlock(&itransfer->lock);
--
--      if (status == LIBUSB_TRANSFER_COMPLETED
--                      && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
--              int rqlen = transfer->length;
--              if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
--                      rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
--              if (rqlen != itransfer->transferred) {
--                      usbi_dbg("interpreting short transfer as error");
--                      status = LIBUSB_TRANSFER_ERROR;
--              }
--      }
--
--      flags = transfer->flags;
--      transfer->status = status;
--      transfer->actual_length = itransfer->transferred;
--      usbi_dbg("transfer %p has callback %p", transfer, transfer->callback);
--      if (transfer->callback)
--              transfer->callback(transfer);
--      /* transfer might have been freed by the above call, do not use from
--       * this point. */
--      if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
--              libusb_free_transfer(transfer);
--      libusb_unref_device(dev_handle->dev);
--      return r;
--}
--
--/* Similar to usbi_handle_transfer_completion() but exclusively for transfers
-- * that were asynchronously cancelled. The same concerns w.r.t. freeing of
-- * transfers exist here.
-- * Do not call this function with the usbi_transfer lock held. User-specified
-- * callback functions may attempt to directly resubmit the transfer, which
-- * will attempt to take the lock. */
- int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
 -int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer)
--{
-       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
 -      struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
--      uint8_t timed_out;
--
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
-       timed_out = transfer->timeout_flags & USBI_TRANSFER_TIMED_OUT;
 -      timed_out = itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT;
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
--
--      /* if the URB was cancelled due to timeout, report timeout to the user */
--      if (timed_out) {
--              usbi_dbg("detected timeout cancellation");
-               return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
 -              return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_TIMED_OUT);
--      }
--
--      /* otherwise its a normal async cancel */
-       return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
 -      return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_CANCELLED);
--}
--
--/* Add a completed transfer to the completed_transfers list of the
-- * context and signal the event. The backend's handle_transfer_completion()
-- * function will be called the next time an event handler runs. */
- void usbi_signal_transfer_completion(struct usbi_transfer *transfer)
 -void usbi_signal_transfer_completion(struct usbi_transfer *itransfer)
--{
-       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
-       int pending_events;
 -      libusb_device_handle *dev_handle = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->dev_handle;
--
-       usbi_mutex_lock(&ctx->event_data_lock);
-       pending_events = usbi_pending_events(ctx);
-       list_add_tail(&transfer->completed_list, &ctx->completed_transfers);
-       if (!pending_events)
-               usbi_signal_event(ctx);
-       usbi_mutex_unlock(&ctx->event_data_lock);
 -      if (dev_handle) {
 -              struct libusb_context *ctx = HANDLE_CTX(dev_handle);
 -              unsigned int event_flags;
 -
 -              usbi_mutex_lock(&ctx->event_data_lock);
 -              event_flags = ctx->event_flags;
 -              ctx->event_flags |= USBI_EVENT_TRANSFER_COMPLETED;
 -              list_add_tail(&itransfer->completed_list, &ctx->completed_transfers);
 -              if (!event_flags)
 -                      usbi_signal_event(&ctx->event);
 -              usbi_mutex_unlock(&ctx->event_data_lock);
 -      }
--}
--
--/** \ingroup libusb_poll
-- * Attempt to acquire the event handling lock. This lock is used to ensure that
-- * only one thread is monitoring libusb event sources at any one time.
-- *
-- * You only need to use this lock if you are developing an application
-- * which calls poll() or select() on libusb's file descriptors directly.
-- * If you stick to libusb's event handling loop functions (e.g.
-- * libusb_handle_events()) then you do not need to be concerned with this
-- * locking.
-- *
-- * While holding this lock, you are trusted to actually be handling events.
-- * If you are no longer handling events, you must call libusb_unlock_events()
-- * as soon as possible.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \returns 0 if the lock was obtained successfully
-- * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
-- * \ref libusb_mtasync
-- */
--int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
--{
--      int r;
--      unsigned int ru;
-       USBI_GET_CONTEXT(ctx);
 -
 -      ctx = usbi_get_context(ctx);
--
--      /* is someone else waiting to close a device? if so, don't let this thread
--       * start event handling */
--      usbi_mutex_lock(&ctx->event_data_lock);
--      ru = ctx->device_close;
--      usbi_mutex_unlock(&ctx->event_data_lock);
--      if (ru) {
--              usbi_dbg("someone else is closing a device");
--              return 1;
--      }
--
--      r = usbi_mutex_trylock(&ctx->events_lock);
-       if (r)
 -      if (!r)
--              return 1;
--
--      ctx->event_handler_active = 1;
--      return 0;
--}
--
--/** \ingroup libusb_poll
-- * Acquire the event handling lock, blocking until successful acquisition if
-- * it is contended. This lock is used to ensure that only one thread is
-- * monitoring libusb event sources at any one time.
-- *
-- * You only need to use this lock if you are developing an application
-- * which calls poll() or select() on libusb's file descriptors directly.
-- * If you stick to libusb's event handling loop functions (e.g.
-- * libusb_handle_events()) then you do not need to be concerned with this
-- * locking.
-- *
-- * While holding this lock, you are trusted to actually be handling events.
-- * If you are no longer handling events, you must call libusb_unlock_events()
-- * as soon as possible.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \ref libusb_mtasync
-- */
--void API_EXPORTED libusb_lock_events(libusb_context *ctx)
--{
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      usbi_mutex_lock(&ctx->events_lock);
--      ctx->event_handler_active = 1;
--}
--
--/** \ingroup libusb_poll
-- * Release the lock previously acquired with libusb_try_lock_events() or
-- * libusb_lock_events(). Releasing this lock will wake up any threads blocked
-- * on libusb_wait_for_event().
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \ref libusb_mtasync
-- */
--void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
--{
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      ctx->event_handler_active = 0;
--      usbi_mutex_unlock(&ctx->events_lock);
--
--      /* FIXME: perhaps we should be a bit more efficient by not broadcasting
--       * the availability of the events lock when we are modifying pollfds
--       * (check ctx->device_close)? */
--      usbi_mutex_lock(&ctx->event_waiters_lock);
--      usbi_cond_broadcast(&ctx->event_waiters_cond);
--      usbi_mutex_unlock(&ctx->event_waiters_lock);
--}
--
--/** \ingroup libusb_poll
-- * Determine if it is still OK for this thread to be doing event handling.
-- *
-- * Sometimes, libusb needs to temporarily pause all event handlers, and this
-- * is the function you should use before polling file descriptors to see if
-- * this is the case.
-- *
-- * If this function instructs your thread to give up the events lock, you
-- * should just continue the usual logic that is documented in \ref libusb_mtasync.
-- * On the next iteration, your thread will fail to obtain the events lock,
-- * and will hence become an event waiter.
-- *
-- * This function should be called while the events lock is held: you don't
-- * need to worry about the results of this function if your thread is not
-- * the current event handler.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \returns 1 if event handling can start or continue
-- * \returns 0 if this thread must give up the events lock
-- * \ref fullstory "Multi-threaded I/O: the full story"
-- */
--int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
--{
--      unsigned int r;
-       USBI_GET_CONTEXT(ctx);
 -
 -      ctx = usbi_get_context(ctx);
--
--      /* is someone else waiting to close a device? if so, don't let this thread
--       * continue event handling */
--      usbi_mutex_lock(&ctx->event_data_lock);
--      r = ctx->device_close;
--      usbi_mutex_unlock(&ctx->event_data_lock);
--      if (r) {
--              usbi_dbg("someone else is closing a device");
--              return 0;
--      }
--
--      return 1;
--}
--
--
--/** \ingroup libusb_poll
-- * Determine if an active thread is handling events (i.e. if anyone is holding
-- * the event handling lock).
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \returns 1 if a thread is handling events
-- * \returns 0 if there are no threads currently handling events
-- * \ref libusb_mtasync
-- */
--int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
--{
--      unsigned int r;
-       USBI_GET_CONTEXT(ctx);
 -
 -      ctx = usbi_get_context(ctx);
--
--      /* is someone else waiting to close a device? if so, don't let this thread
--       * start event handling -- indicate that event handling is happening */
--      usbi_mutex_lock(&ctx->event_data_lock);
--      r = ctx->device_close;
--      usbi_mutex_unlock(&ctx->event_data_lock);
--      if (r) {
--              usbi_dbg("someone else is closing a device");
--              return 1;
--      }
--
--      return ctx->event_handler_active;
--}
--
--/** \ingroup libusb_poll
-- * Interrupt any active thread that is handling events. This is mainly useful
-- * for interrupting a dedicated event handling thread when an application
-- * wishes to call libusb_exit().
-- *
-- * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \ref libusb_mtasync
-- */
--void API_EXPORTED libusb_interrupt_event_handler(libusb_context *ctx)
--{
-       int pending_events;
-       USBI_GET_CONTEXT(ctx);
 -      unsigned int event_flags;
--
-       usbi_dbg("");
 -      usbi_dbg(" ");
 -
 -      ctx = usbi_get_context(ctx);
--      usbi_mutex_lock(&ctx->event_data_lock);
--
-       pending_events = usbi_pending_events(ctx);
 -      event_flags = ctx->event_flags;
--      ctx->event_flags |= USBI_EVENT_USER_INTERRUPT;
-       if (!pending_events)
-               usbi_signal_event(ctx);
 -      if (!event_flags)
 -              usbi_signal_event(&ctx->event);
--
--      usbi_mutex_unlock(&ctx->event_data_lock);
--}
--
--/** \ingroup libusb_poll
-- * Acquire the event waiters lock. This lock is designed to be obtained under
-- * the situation where you want to be aware when events are completed, but
-- * some other thread is event handling so calling libusb_handle_events() is not
-- * allowed.
-- *
-- * You then obtain this lock, re-check that another thread is still handling
-- * events, then call libusb_wait_for_event().
-- *
-- * You only need to use this lock if you are developing an application
-- * which calls poll() or select() on libusb's file descriptors directly,
-  * <b>and</b> may potentially be handling events from 2 threads simultaenously.
 - * <b>and</b> may potentially be handling events from 2 threads simultaneously.
-- * If you stick to libusb's event handling loop functions (e.g.
-- * libusb_handle_events()) then you do not need to be concerned with this
-- * locking.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \ref libusb_mtasync
-- */
--void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
--{
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      usbi_mutex_lock(&ctx->event_waiters_lock);
--}
--
--/** \ingroup libusb_poll
-- * Release the event waiters lock.
-- * \param ctx the context to operate on, or NULL for the default context
-- * \ref libusb_mtasync
-- */
--void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
--{
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      usbi_mutex_unlock(&ctx->event_waiters_lock);
--}
--
--/** \ingroup libusb_poll
-- * Wait for another thread to signal completion of an event. Must be called
-- * with the event waiters lock held, see libusb_lock_event_waiters().
-- *
-- * This function will block until any of the following conditions are met:
-- * -# The timeout expires
-- * -# A transfer completes
-- * -# A thread releases the event handling lock through libusb_unlock_events()
-- *
-- * Condition 1 is obvious. Condition 2 unblocks your thread <em>after</em>
-- * the callback for the transfer has completed. Condition 3 is important
-- * because it means that the thread that was previously handling events is no
-- * longer doing so, so if any events are to complete, another thread needs to
-- * step up and start event handling.
-- *
-- * This function releases the event waiters lock before putting your thread
-- * to sleep, and reacquires the lock as it is being woken up.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param tv maximum timeout for this blocking function. A NULL value
-- * indicates unlimited timeout.
-- * \returns 0 after a transfer completes or another thread stops event handling
-- * \returns 1 if the timeout expired
 - * \returns LIBUSB_ERROR_INVALID_PARAM if timeval is invalid
-- * \ref libusb_mtasync
-- */
--int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
--{
--      int r;
--
-       USBI_GET_CONTEXT(ctx);
-       if (tv == NULL) {
 -      ctx = usbi_get_context(ctx);
 -      if (!tv) {
--              usbi_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
--              return 0;
--      }
 -
 -      if (!TIMEVAL_IS_VALID(tv))
 -              return LIBUSB_ERROR_INVALID_PARAM;
--
--      r = usbi_cond_timedwait(&ctx->event_waiters_cond,
--              &ctx->event_waiters_lock, tv);
--      if (r < 0)
-               return r;
-       else
-               return (r == ETIMEDOUT);
 -              return r == LIBUSB_ERROR_TIMEOUT;
 -
 -      return 0;
--}
--
--static void handle_timeout(struct usbi_transfer *itransfer)
--{
--      struct libusb_transfer *transfer =
--              USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--      int r;
--
--      itransfer->timeout_flags |= USBI_TRANSFER_TIMEOUT_HANDLED;
--      r = libusb_cancel_transfer(transfer);
--      if (r == LIBUSB_SUCCESS)
--              itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
--      else
--              usbi_warn(TRANSFER_CTX(transfer),
-                       "async cancel failed %d errno=%d", r, errno);
 -                      "async cancel failed %d", r);
--}
--
- static int handle_timeouts_locked(struct libusb_context *ctx)
 -static void handle_timeouts_locked(struct libusb_context *ctx)
--{
-       int r;
-       struct timespec systime_ts;
-       struct timeval systime;
-       struct usbi_transfer *transfer;
 -      struct timespec systime;
 -      struct usbi_transfer *itransfer;
--
--      if (list_empty(&ctx->flying_transfers))
-               return 0;
 -              return;
--
--      /* get current time */
-       r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, &systime_ts);
-       if (r < 0)
-               return r;
-       TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
 -      usbi_get_monotonic_time(&systime);
--
--      /* iterate through flying transfers list, finding all transfers that
--       * have expired timeouts */
-       list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
-               struct timeval *cur_tv = &transfer->timeout;
 -      for_each_transfer(ctx, itransfer) {
 -              struct timespec *cur_ts = &itransfer->timeout;
--
--              /* if we've reached transfers of infinite timeout, we're all done */
-               if (!timerisset(cur_tv))
-                       return 0;
 -              if (!TIMESPEC_IS_SET(cur_ts))
 -                      return;
--
--              /* ignore timeouts we've already handled */
-               if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
 -              if (itransfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
--                      continue;
--
--              /* if transfer has non-expired timeout, nothing more to do */
-               if ((cur_tv->tv_sec > systime.tv_sec) ||
-                               (cur_tv->tv_sec == systime.tv_sec &&
-                                       cur_tv->tv_usec > systime.tv_usec))
-                       return 0;
 -              if (TIMESPEC_CMP(cur_ts, &systime, >))
 -                      return;
--
--              /* otherwise, we've got an expired timeout to handle */
-               handle_timeout(transfer);
 -              handle_timeout(itransfer);
--      }
-       return 0;
--}
--
- static int handle_timeouts(struct libusb_context *ctx)
 -static void handle_timeouts(struct libusb_context *ctx)
--{
-       int r;
-       USBI_GET_CONTEXT(ctx);
 -      ctx = usbi_get_context(ctx);
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
-       r = handle_timeouts_locked(ctx);
 -      handle_timeouts_locked(ctx);
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
 -}
 -
 -static int handle_event_trigger(struct libusb_context *ctx)
 -{
 -      struct list_head hotplug_msgs;
 -      int r = 0;
 -
 -      usbi_dbg("event triggered");
 -
 -      list_init(&hotplug_msgs);
 -
 -      /* take the the event data lock while processing events */
 -      usbi_mutex_lock(&ctx->event_data_lock);
 -
 -      /* check if someone modified the event sources */
 -      if (ctx->event_flags & USBI_EVENT_EVENT_SOURCES_MODIFIED)
 -              usbi_dbg("someone updated the event sources");
 -
 -      if (ctx->event_flags & USBI_EVENT_USER_INTERRUPT) {
 -              usbi_dbg("someone purposefully interrupted");
 -              ctx->event_flags &= ~USBI_EVENT_USER_INTERRUPT;
 -      }
 -
 -      /* check if someone is closing a device */
 -      if (ctx->event_flags & USBI_EVENT_DEVICE_CLOSE)
 -              usbi_dbg("someone is closing a device");
 -
 -      /* check for any pending hotplug messages */
 -      if (ctx->event_flags & USBI_EVENT_HOTPLUG_MSG_PENDING) {
 -              usbi_dbg("hotplug message received");
 -              ctx->event_flags &= ~USBI_EVENT_HOTPLUG_MSG_PENDING;
 -              assert(!list_empty(&ctx->hotplug_msgs));
 -              list_cut(&hotplug_msgs, &ctx->hotplug_msgs);
 -      }
 -
 -      /* complete any pending transfers */
 -      if (ctx->event_flags & USBI_EVENT_TRANSFER_COMPLETED) {
 -              struct usbi_transfer *itransfer, *tmp;
 -              struct list_head completed_transfers;
 -
 -              assert(!list_empty(&ctx->completed_transfers));
 -              list_cut(&completed_transfers, &ctx->completed_transfers);
 -              usbi_mutex_unlock(&ctx->event_data_lock);
 -
 -              __for_each_completed_transfer_safe(&completed_transfers, itransfer, tmp) {
 -                      list_del(&itransfer->completed_list);
 -                      r = usbi_backend.handle_transfer_completion(itransfer);
 -                      if (r) {
 -                              usbi_err(ctx, "backend handle_transfer_completion failed with error %d", r);
 -                              break;
 -                      }
 -              }
 -
 -              usbi_mutex_lock(&ctx->event_data_lock);
 -              if (!list_empty(&completed_transfers)) {
 -                      /* an error occurred, put the remaining transfers back on the list */
 -                      list_splice_front(&completed_transfers, &ctx->completed_transfers);
 -              } else if (list_empty(&ctx->completed_transfers)) {
 -                      ctx->event_flags &= ~USBI_EVENT_TRANSFER_COMPLETED;
 -              }
 -      }
 -
 -      /* if no further pending events, clear the event */
 -      if (!ctx->event_flags)
 -              usbi_clear_event(&ctx->event);
 -
 -      usbi_mutex_unlock(&ctx->event_data_lock);
 -
 -      /* process the hotplug messages, if any */
 -      while (!list_empty(&hotplug_msgs)) {
 -              struct libusb_hotplug_message *message =
 -                      list_first_entry(&hotplug_msgs, struct libusb_hotplug_message, list);
 -
 -              usbi_hotplug_match(ctx, message->device, message->event);
 -
 -              /* the device left, dereference the device */
 -              if (message->event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
 -                      libusb_unref_device(message->device);
 -
 -              list_del(&message->list);
 -              free(message);
 -      }
 -
--      return r;
--}
--
- #ifdef USBI_TIMERFD_AVAILABLE
- static int handle_timerfd_trigger(struct libusb_context *ctx)
 -#ifdef HAVE_OS_TIMER
 -static int handle_timer_trigger(struct libusb_context *ctx)
--{
--      int r;
--
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
--
--      /* process the timeout that just happened */
-       r = handle_timeouts_locked(ctx);
-       if (r < 0)
-               goto out;
 -      handle_timeouts_locked(ctx);
--
-       /* arm for next timeout*/
-       r = arm_timerfd_for_next_timeout(ctx);
 -      /* arm for next timeout */
 -      r = arm_timer_for_next_timeout(ctx);
--
- out:
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
 -
--      return r;
--}
--#endif
--
--/* do the actual event handling. assumes that no other thread is concurrently
-- * doing the same thing. */
--static int handle_events(struct libusb_context *ctx, struct timeval *tv)
--{
-       int r;
-       struct usbi_pollfd *ipollfd;
-       POLL_NFDS_TYPE nfds = 0;
-       POLL_NFDS_TYPE internal_nfds;
-       struct pollfd *fds = NULL;
-       int i = -1;
-       int timeout_ms;
 -      struct usbi_reported_events reported_events;
 -      int r, timeout_ms;
--
--      /* prevent attempts to recursively handle events (e.g. calling into
--       * libusb_handle_events() from within a hotplug or transfer callback) */
--      if (usbi_handling_events(ctx))
--              return LIBUSB_ERROR_BUSY;
-       usbi_start_event_handling(ctx);
-       /* there are certain fds that libusb uses internally, currently:
-        *
-        *   1) event pipe
-        *   2) timerfd
-        *
-        * the backend will never need to attempt to handle events on these fds, so
-        * we determine how many fds are in use internally for this context and when
-        * handle_events() is called in the backend, the pollfd list and count will
-        * be adjusted to skip over these internal fds */
-       if (usbi_using_timerfd(ctx))
-               internal_nfds = 2;
-       else
-               internal_nfds = 1;
--
-       /* only reallocate the poll fds when the list of poll fds has been modified
-        * since the last poll, otherwise reuse them to save the additional overhead */
 -      /* only reallocate the event source data when the list of event sources has
 -       * been modified since the last handle_events(), otherwise reuse them to
 -       * save the additional overhead */
--      usbi_mutex_lock(&ctx->event_data_lock);
-       if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED) {
-               usbi_dbg("poll fds modified, reallocating");
-               if (ctx->pollfds) {
-                       free(ctx->pollfds);
-                       ctx->pollfds = NULL;
-               }
 -      if (ctx->event_flags & USBI_EVENT_EVENT_SOURCES_MODIFIED) {
 -              usbi_dbg("event sources modified, reallocating event data");
--
-               /* sanity check - it is invalid for a context to have fewer than the
-                * required internal fds (memory corruption?) */
-               assert(ctx->pollfds_cnt >= internal_nfds);
 -              /* free anything removed since we last ran */
 -              cleanup_removed_event_sources(ctx);
--
-               ctx->pollfds = calloc(ctx->pollfds_cnt, sizeof(*ctx->pollfds));
-               if (!ctx->pollfds) {
 -              r = usbi_alloc_event_data(ctx);
 -              if (r) {
--                      usbi_mutex_unlock(&ctx->event_data_lock);
-                       r = LIBUSB_ERROR_NO_MEM;
-                       goto done;
-               }
-               list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) {
-                       struct libusb_pollfd *pollfd = &ipollfd->pollfd;
-                       i++;
-                       ctx->pollfds[i].fd = pollfd->fd;
-                       ctx->pollfds[i].events = pollfd->events;
 -                      return r;
--              }
--
--              /* reset the flag now that we have the updated list */
-               ctx->event_flags &= ~USBI_EVENT_POLLFDS_MODIFIED;
 -              ctx->event_flags &= ~USBI_EVENT_EVENT_SOURCES_MODIFIED;
--
-               /* if no further pending events, clear the event pipe so that we do
-                * not immediately return from poll */
-               if (!usbi_pending_events(ctx))
-                       usbi_clear_event(ctx);
 -              /* if no further pending events, clear the event so that we do
 -               * not immediately return from the wait function */
 -              if (!ctx->event_flags)
 -                      usbi_clear_event(&ctx->event);
--      }
-       fds = ctx->pollfds;
-       nfds = ctx->pollfds_cnt;
--      usbi_mutex_unlock(&ctx->event_data_lock);
--
--      timeout_ms = (int)(tv->tv_sec * 1000) + (tv->tv_usec / 1000);
--
--      /* round up to next millisecond */
--      if (tv->tv_usec % 1000)
--              timeout_ms++;
-       usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
-       r = usbi_poll(fds, nfds, timeout_ms);
-       usbi_dbg("poll() returned %d", r);
-       if (r == 0) {
-               r = handle_timeouts(ctx);
-               goto done;
-       } else if (r == -1 && errno == EINTR) {
-               r = LIBUSB_ERROR_INTERRUPTED;
-               goto done;
-       } else if (r < 0) {
-               usbi_err(ctx, "poll failed %d err=%d", r, errno);
-               r = LIBUSB_ERROR_IO;
-               goto done;
-       }
-       /* fds[0] is always the event pipe */
-       if (fds[0].revents) {
-               struct list_head hotplug_msgs;
-               struct usbi_transfer *itransfer;
-               int hotplug_cb_deregistered = 0;
-               int ret = 0;
-               list_init(&hotplug_msgs);
-               usbi_dbg("caught a fish on the event pipe");
-               /* take the the event data lock while processing events */
-               usbi_mutex_lock(&ctx->event_data_lock);
-               /* check if someone added a new poll fd */
-               if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED)
-                       usbi_dbg("someone updated the poll fds");
-               if (ctx->event_flags & USBI_EVENT_USER_INTERRUPT) {
-                       usbi_dbg("someone purposely interrupted");
-                       ctx->event_flags &= ~USBI_EVENT_USER_INTERRUPT;
-               }
-               if (ctx->event_flags & USBI_EVENT_HOTPLUG_CB_DEREGISTERED) {
-                       usbi_dbg("someone unregistered a hotplug cb");
-                       ctx->event_flags &= ~USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
-                       hotplug_cb_deregistered = 1;
-               }
-               /* check if someone is closing a device */
-               if (ctx->device_close)
-                       usbi_dbg("someone is closing a device");
-               /* check for any pending hotplug messages */
-               if (!list_empty(&ctx->hotplug_msgs)) {
-                       usbi_dbg("hotplug message received");
-                       list_cut(&hotplug_msgs, &ctx->hotplug_msgs);
-               }
-               /* complete any pending transfers */
-               while (ret == 0 && !list_empty(&ctx->completed_transfers)) {
-                       itransfer = list_first_entry(&ctx->completed_transfers, struct usbi_transfer, completed_list);
-                       list_del(&itransfer->completed_list);
-                       usbi_mutex_unlock(&ctx->event_data_lock);
-                       ret = usbi_backend.handle_transfer_completion(itransfer);
-                       if (ret)
-                               usbi_err(ctx, "backend handle_transfer_completion failed with error %d", ret);
-                       usbi_mutex_lock(&ctx->event_data_lock);
-               }
-               /* if no further pending events, clear the event pipe */
-               if (!usbi_pending_events(ctx))
-                       usbi_clear_event(ctx);
-               usbi_mutex_unlock(&ctx->event_data_lock);
-               if (hotplug_cb_deregistered)
-                       usbi_hotplug_deregister(ctx, 0);
-               /* process the hotplug messages, if any */
-               while (!list_empty(&hotplug_msgs)) {
-                       struct libusb_hotplug_message *message =
-                               list_first_entry(&hotplug_msgs, struct libusb_hotplug_message, list);
--
-                       usbi_hotplug_match(ctx, message->device, message->event);
 -      reported_events.event_bits = 0;
--
-                       /* the device left, dereference the device */
-                       if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message->event)
-                               libusb_unref_device(message->device);
 -      usbi_start_event_handling(ctx);
--
-                       list_del(&message->list);
-                       free(message);
 -      r = usbi_wait_for_events(ctx, &reported_events, timeout_ms);
 -      if (r != LIBUSB_SUCCESS) {
 -              if (r == LIBUSB_ERROR_TIMEOUT) {
 -                      handle_timeouts(ctx);
 -                      r = LIBUSB_SUCCESS;
--              }
 -              goto done;
 -      }
--
-               if (ret) {
 -      if (reported_events.event_triggered) {
 -              r = handle_event_trigger(ctx);
 -              if (r) {
--                      /* return error code */
-                       r = ret;
--                      goto done;
--              }
-               if (0 == --r)
-                       goto done;
--      }
- #ifdef USBI_TIMERFD_AVAILABLE
-       /* on timerfd configurations, fds[1] is the timerfd */
-       if (usbi_using_timerfd(ctx) && fds[1].revents) {
-               /* timerfd indicates that a timeout has expired */
-               int ret;
-               usbi_dbg("timerfd triggered");
--
-               ret = handle_timerfd_trigger(ctx);
-               if (ret < 0) {
 -#ifdef HAVE_OS_TIMER
 -      if (reported_events.timer_triggered) {
 -              r = handle_timer_trigger(ctx);
 -              if (r) {
--                      /* return error code */
-                       r = ret;
--                      goto done;
--              }
-               if (0 == --r)
-                       goto done;
--      }
--#endif
--
-       r = usbi_backend.handle_events(ctx, fds + internal_nfds, nfds - internal_nfds, r);
 -      if (!reported_events.num_ready)
 -              goto done;
 -
 -      r = usbi_backend.handle_events(ctx, reported_events.event_data,
 -              reported_events.event_data_count, reported_events.num_ready);
--      if (r)
--              usbi_err(ctx, "backend handle_events failed with error %d", r);
--
--done:
--      usbi_end_event_handling(ctx);
--      return r;
--}
--
--/* returns the smallest of:
-- *  1. timeout of next URB
-- *  2. user-supplied timeout
-- * returns 1 if there is an already-expired timeout, otherwise returns 0
-- * and populates out
-- */
--static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
--      struct timeval *out)
--{
--      struct timeval timeout;
--      int r = libusb_get_next_timeout(ctx, &timeout);
--      if (r) {
--              /* timeout already expired? */
--              if (!timerisset(&timeout))
--                      return 1;
--
--              /* choose the smallest of next URB timeout or user specified timeout */
--              if (timercmp(&timeout, tv, <))
--                      *out = timeout;
--              else
--                      *out = *tv;
--      } else {
--              *out = *tv;
--      }
--      return 0;
--}
--
--/** \ingroup libusb_poll
-- * Handle any pending events.
-- *
-- * libusb determines "pending events" by checking if any timeouts have expired
-- * and by checking the set of file descriptors for activity.
-- *
-- * If a zero timeval is passed, this function will handle any already-pending
-- * events and then immediately return in non-blocking style.
-- *
-- * If a non-zero timeval is passed and no events are currently pending, this
-- * function will block waiting for events to handle up until the specified
-- * timeout. If an event arrives or a signal is raised, this function will
-- * return early.
-- *
-- * If the parameter completed is not NULL then <em>after obtaining the event
-- * handling lock</em> this function will return immediately if the integer
-- * pointed to is not 0. This allows for race free waiting for the completion
-- * of a specific transfer.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param tv the maximum time to block waiting for events, or an all zero
-- * timeval struct for non-blocking mode
-- * \param completed pointer to completion integer to check, or NULL
-  * \returns 0 on success, or a LIBUSB_ERROR code on failure
 - * \returns 0 on success
 - * \returns LIBUSB_ERROR_INVALID_PARAM if timeval is invalid
 - * \returns another LIBUSB_ERROR code on other failure
-- * \ref libusb_mtasync
-- */
--int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx,
--      struct timeval *tv, int *completed)
--{
--      int r;
--      struct timeval poll_timeout;
--
-       USBI_GET_CONTEXT(ctx);
 -      if (!TIMEVAL_IS_VALID(tv))
 -              return LIBUSB_ERROR_INVALID_PARAM;
 -
 -      ctx = usbi_get_context(ctx);
--      r = get_next_timeout(ctx, tv, &poll_timeout);
--      if (r) {
--              /* timeout already expired */
-               return handle_timeouts(ctx);
 -              handle_timeouts(ctx);
 -              return 0;
--      }
--
--retry:
--      if (libusb_try_lock_events(ctx) == 0) {
--              if (completed == NULL || !*completed) {
--                      /* we obtained the event lock: do our own event handling */
--                      usbi_dbg("doing our own event handling");
--                      r = handle_events(ctx, &poll_timeout);
--              }
--              libusb_unlock_events(ctx);
--              return r;
--      }
--
--      /* another thread is doing event handling. wait for thread events that
--       * notify event completion. */
--      libusb_lock_event_waiters(ctx);
--
--      if (completed && *completed)
--              goto already_done;
--
--      if (!libusb_event_handler_active(ctx)) {
--              /* we hit a race: whoever was event handling earlier finished in the
--               * time it took us to reach this point. try the cycle again. */
--              libusb_unlock_event_waiters(ctx);
--              usbi_dbg("event handler was active but went away, retrying");
--              goto retry;
--      }
--
--      usbi_dbg("another thread is doing event handling");
--      r = libusb_wait_for_event(ctx, &poll_timeout);
--
--already_done:
--      libusb_unlock_event_waiters(ctx);
--
--      if (r < 0)
--              return r;
--      else if (r == 1)
-               return handle_timeouts(ctx);
-       else
-               return 0;
 -              handle_timeouts(ctx);
 -      return 0;
--}
--
--/** \ingroup libusb_poll
-- * Handle any pending events
-- *
-- * Like libusb_handle_events_timeout_completed(), but without the completed
-- * parameter, calling this function is equivalent to calling
-- * libusb_handle_events_timeout_completed() with a NULL completed parameter.
-- *
-- * This function is kept primarily for backwards compatibility.
-- * All new code should call libusb_handle_events_completed() or
-- * libusb_handle_events_timeout_completed() to avoid race conditions.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param tv the maximum time to block waiting for events, or an all zero
-- * timeval struct for non-blocking mode
-- * \returns 0 on success, or a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_handle_events_timeout(libusb_context *ctx,
--      struct timeval *tv)
--{
--      return libusb_handle_events_timeout_completed(ctx, tv, NULL);
--}
--
--/** \ingroup libusb_poll
-- * Handle any pending events in blocking mode. There is currently a timeout
-  * hardcoded at 60 seconds but we plan to make it unlimited in future. For
 - * hard-coded at 60 seconds but we plan to make it unlimited in future. For
-- * finer control over whether this function is blocking or non-blocking, or
-- * for control over the timeout, use libusb_handle_events_timeout_completed()
-- * instead.
-- *
-- * This function is kept primarily for backwards compatibility.
-- * All new code should call libusb_handle_events_completed() or
-- * libusb_handle_events_timeout_completed() to avoid race conditions.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \returns 0 on success, or a LIBUSB_ERROR code on failure
-- */
--int API_EXPORTED libusb_handle_events(libusb_context *ctx)
--{
--      struct timeval tv;
--      tv.tv_sec = 60;
--      tv.tv_usec = 0;
--      return libusb_handle_events_timeout_completed(ctx, &tv, NULL);
--}
--
--/** \ingroup libusb_poll
-- * Handle any pending events in blocking mode.
-- *
-- * Like libusb_handle_events(), with the addition of a completed parameter
-- * to allow for race free waiting for the completion of a specific transfer.
-- *
-- * See libusb_handle_events_timeout_completed() for details on the completed
-- * parameter.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param completed pointer to completion integer to check, or NULL
-- * \returns 0 on success, or a LIBUSB_ERROR code on failure
-- * \ref libusb_mtasync
-- */
--int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx,
--      int *completed)
--{
--      struct timeval tv;
--      tv.tv_sec = 60;
--      tv.tv_usec = 0;
--      return libusb_handle_events_timeout_completed(ctx, &tv, completed);
--}
--
--/** \ingroup libusb_poll
-- * Handle any pending events by polling file descriptors, without checking if
-- * any other threads are already doing so. Must be called with the event lock
-- * held, see libusb_lock_events().
-- *
-- * This function is designed to be called under the situation where you have
-- * taken the event lock and are calling poll()/select() directly on libusb's
-- * file descriptors (as opposed to using libusb_handle_events() or similar).
-- * You detect events on libusb's descriptors, so you then call this function
-- * with a zero timeout value (while still holding the event lock).
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param tv the maximum time to block waiting for events, or zero for
-- * non-blocking mode
-  * \returns 0 on success, or a LIBUSB_ERROR code on failure
 - * \returns 0 on success
 - * \returns LIBUSB_ERROR_INVALID_PARAM if timeval is invalid
 - * \returns another LIBUSB_ERROR code on other failure
-- * \ref libusb_mtasync
-- */
--int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx,
--      struct timeval *tv)
--{
--      int r;
--      struct timeval poll_timeout;
--
-       USBI_GET_CONTEXT(ctx);
 -      if (!TIMEVAL_IS_VALID(tv))
 -              return LIBUSB_ERROR_INVALID_PARAM;
 -
 -      ctx = usbi_get_context(ctx);
--      r = get_next_timeout(ctx, tv, &poll_timeout);
--      if (r) {
--              /* timeout already expired */
-               return handle_timeouts(ctx);
 -              handle_timeouts(ctx);
 -              return 0;
--      }
--
--      return handle_events(ctx, &poll_timeout);
--}
--
--/** \ingroup libusb_poll
-- * Determines whether your application must apply special timing considerations
-- * when monitoring libusb's file descriptors.
-- *
-- * This function is only useful for applications which retrieve and poll
-- * libusb's file descriptors in their own main loop (\ref libusb_pollmain).
-- *
-- * Ordinarily, libusb's event handler needs to be called into at specific
-- * moments in time (in addition to times when there is activity on the file
-- * descriptor set). The usual approach is to use libusb_get_next_timeout()
-- * to learn about when the next timeout occurs, and to adjust your
-- * poll()/select() timeout accordingly so that you can make a call into the
-- * library at that time.
-- *
-- * Some platforms supported by libusb do not come with this baggage - any
-- * events relevant to timing will be represented by activity on the file
-- * descriptor set, and libusb_get_next_timeout() will always return 0.
-- * This function allows you to detect whether you are running on such a
-- * platform.
-- *
-- * Since v1.0.5.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \returns 0 if you must call into libusb at times determined by
-- * libusb_get_next_timeout(), or 1 if all timeout events are handled internally
-- * or through regular activity on the file descriptors.
-- * \ref libusb_pollmain "Polling libusb file descriptors for event handling"
-- */
--int API_EXPORTED libusb_pollfds_handle_timeouts(libusb_context *ctx)
--{
- #if defined(USBI_TIMERFD_AVAILABLE)
-       USBI_GET_CONTEXT(ctx);
-       return usbi_using_timerfd(ctx);
- #else
-       UNUSED(ctx);
-       return 0;
- #endif
 -      ctx = usbi_get_context(ctx);
 -      return usbi_using_timer(ctx);
--}
--
--/** \ingroup libusb_poll
-- * Determine the next internal timeout that libusb needs to handle. You only
-- * need to use this function if you are calling poll() or select() or similar
-- * on libusb's file descriptors yourself - you do not need to use it if you
-- * are calling libusb_handle_events() or a variant directly.
-- *
-- * You should call this function in your main loop in order to determine how
-- * long to wait for select() or poll() to return results. libusb needs to be
-- * called into at this timeout, so you should use it as an upper bound on
-- * your select() or poll() call.
-- *
-- * When the timeout has expired, call into libusb_handle_events_timeout()
-- * (perhaps in non-blocking mode) so that libusb can handle the timeout.
-- *
-- * This function may return 1 (success) and an all-zero timeval. If this is
-- * the case, it indicates that libusb has a timeout that has already expired
-- * so you should call libusb_handle_events_timeout() or similar immediately.
-- * A return code of 0 indicates that there are no pending timeouts.
-- *
-- * On some platforms, this function will always returns 0 (no pending
-- * timeouts). See \ref polltime.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param tv output location for a relative time against the current
-- * clock in which libusb must be called into in order to process timeout events
-- * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
-- * or LIBUSB_ERROR_OTHER on failure
-- */
--int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
--      struct timeval *tv)
--{
-       struct usbi_transfer *transfer;
-       struct timespec cur_ts;
-       struct timeval cur_tv;
-       struct timeval next_timeout = { 0, 0 };
-       int r;
 -      struct usbi_transfer *itransfer;
 -      struct timespec systime;
 -      struct timespec next_timeout = { 0, 0 };
--
-       USBI_GET_CONTEXT(ctx);
-       if (usbi_using_timerfd(ctx))
 -      ctx = usbi_get_context(ctx);
 -      if (usbi_using_timer(ctx))
--              return 0;
--
--      usbi_mutex_lock(&ctx->flying_transfers_lock);
--      if (list_empty(&ctx->flying_transfers)) {
--              usbi_mutex_unlock(&ctx->flying_transfers_lock);
--              usbi_dbg("no URBs, no timeout!");
--              return 0;
--      }
--
--      /* find next transfer which hasn't already been processed as timed out */
-       list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
-               if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
 -      for_each_transfer(ctx, itransfer) {
 -              if (itransfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
--                      continue;
--
-               /* if we've reached transfers of infinte timeout, we're done looking */
-               if (!timerisset(&transfer->timeout))
 -              /* if we've reached transfers of infinite timeout, we're done looking */
 -              if (!TIMESPEC_IS_SET(&itransfer->timeout))
--                      break;
--
-               next_timeout = transfer->timeout;
 -              next_timeout = itransfer->timeout;
--              break;
--      }
--      usbi_mutex_unlock(&ctx->flying_transfers_lock);
--
-       if (!timerisset(&next_timeout)) {
 -      if (!TIMESPEC_IS_SET(&next_timeout)) {
--              usbi_dbg("no URB with timeout or all handled by OS; no timeout!");
--              return 0;
--      }
--
-       r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, &cur_ts);
-       if (r < 0) {
-               usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
-               return 0;
-       }
-       TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
 -      usbi_get_monotonic_time(&systime);
--
-       if (!timercmp(&cur_tv, &next_timeout, <)) {
 -      if (!TIMESPEC_CMP(&systime, &next_timeout, <)) {
--              usbi_dbg("first timeout already expired");
--              timerclear(tv);
--      } else {
-               timersub(&next_timeout, &cur_tv, tv);
-               usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
 -              TIMESPEC_SUB(&next_timeout, &systime, &next_timeout);
 -              TIMESPEC_TO_TIMEVAL(tv, &next_timeout);
 -              usbi_dbg("next timeout in %ld.%06lds", (long)tv->tv_sec, (long)tv->tv_usec);
--      }
--
--      return 1;
--}
--
--/** \ingroup libusb_poll
-- * Register notification functions for file descriptor additions/removals.
-- * These functions will be invoked for every new or removed file descriptor
-- * that libusb uses as an event source.
-- *
-- * To remove notifiers, pass NULL values for the function pointers.
-- *
-- * Note that file descriptors may have been added even before you register
-- * these notifiers (e.g. at libusb_init() time).
-- *
-- * Additionally, note that the removal notifier may be called during
-- * libusb_exit() (e.g. when it is closing file descriptors that were opened
-- * and added to the poll set at libusb_init() time). If you don't want this,
-- * remove the notifiers immediately before calling libusb_exit().
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \param added_cb pointer to function for addition notifications
-- * \param removed_cb pointer to function for removal notifications
-- * \param user_data User data to be passed back to callbacks (useful for
-- * passing context information)
-- */
--void API_EXPORTED libusb_set_pollfd_notifiers(libusb_context *ctx,
--      libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
--      void *user_data)
--{
-       USBI_GET_CONTEXT(ctx);
 -#if !defined(PLATFORM_WINDOWS)
 -      ctx = usbi_get_context(ctx);
--      ctx->fd_added_cb = added_cb;
--      ctx->fd_removed_cb = removed_cb;
--      ctx->fd_cb_user_data = user_data;
 -#else
 -      usbi_err(ctx, "external polling of libusb's internal event sources " \
 -              "is not yet supported on Windows");
 -      UNUSED(added_cb);
 -      UNUSED(removed_cb);
 -      UNUSED(user_data);
 -#endif
--}
--
--/*
-- * Interrupt the iteration of the event handling thread, so that it picks
-  * up the fd change. Callers of this function must hold the event_data_lock.
 - * up the event source change. Callers of this function must hold the event_data_lock.
-- */
- static void usbi_fd_notification(struct libusb_context *ctx)
 -static void usbi_event_source_notification(struct libusb_context *ctx)
--{
-       int pending_events;
 -      unsigned int event_flags;
--
--      /* Record that there is a new poll fd.
--       * Only signal an event if there are no prior pending events. */
-       pending_events = usbi_pending_events(ctx);
-       ctx->event_flags |= USBI_EVENT_POLLFDS_MODIFIED;
-       if (!pending_events)
-               usbi_signal_event(ctx);
 -      event_flags = ctx->event_flags;
 -      ctx->event_flags |= USBI_EVENT_EVENT_SOURCES_MODIFIED;
 -      if (!event_flags)
 -              usbi_signal_event(&ctx->event);
--}
--
- /* Add a file descriptor to the list of file descriptors to be monitored.
-  * events should be specified as a bitmask of events passed to poll(), e.g.
 -/* Add an event source to the list of event sources to be monitored.
 - * poll_events should be specified as a bitmask of events passed to poll(), e.g.
-- * POLLIN and/or POLLOUT. */
- int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
 -int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle, short poll_events)
--{
-       struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
-       if (!ipollfd)
 -      struct usbi_event_source *ievent_source = malloc(sizeof(*ievent_source));
 -
 -      if (!ievent_source)
--              return LIBUSB_ERROR_NO_MEM;
--
-       usbi_dbg("add fd %d events %d", fd, events);
-       ipollfd->pollfd.fd = fd;
-       ipollfd->pollfd.events = events;
 -      usbi_dbg("add " USBI_OS_HANDLE_FORMAT_STRING " events %d", os_handle, poll_events);
 -      ievent_source->data.os_handle = os_handle;
 -      ievent_source->data.poll_events = poll_events;
--      usbi_mutex_lock(&ctx->event_data_lock);
-       list_add_tail(&ipollfd->list, &ctx->ipollfds);
-       ctx->pollfds_cnt++;
-       usbi_fd_notification(ctx);
 -      list_add_tail(&ievent_source->list, &ctx->event_sources);
 -      usbi_event_source_notification(ctx);
--      usbi_mutex_unlock(&ctx->event_data_lock);
--
 -#if !defined(PLATFORM_WINDOWS)
--      if (ctx->fd_added_cb)
-               ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
 -              ctx->fd_added_cb(os_handle, poll_events, ctx->fd_cb_user_data);
 -#endif
 -
--      return 0;
--}
--
- /* Remove a file descriptor from the list of file descriptors to be polled. */
- void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
 -/* Remove an event source from the list of event sources to be monitored. */
 -void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle)
--{
-       struct usbi_pollfd *ipollfd;
 -      struct usbi_event_source *ievent_source;
--      int found = 0;
--
-       usbi_dbg("remove fd %d", fd);
 -      usbi_dbg("remove " USBI_OS_HANDLE_FORMAT_STRING, os_handle);
--      usbi_mutex_lock(&ctx->event_data_lock);
-       list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
-               if (ipollfd->pollfd.fd == fd) {
 -      for_each_event_source(ctx, ievent_source) {
 -              if (ievent_source->data.os_handle == os_handle) {
--                      found = 1;
--                      break;
--              }
 -      }
--
--      if (!found) {
-               usbi_dbg("couldn't find fd %d to remove", fd);
 -              usbi_dbg("couldn't find " USBI_OS_HANDLE_FORMAT_STRING " to remove", os_handle);
--              usbi_mutex_unlock(&ctx->event_data_lock);
--              return;
--      }
--
-       list_del(&ipollfd->list);
-       ctx->pollfds_cnt--;
-       usbi_fd_notification(ctx);
 -      list_del(&ievent_source->list);
 -      list_add_tail(&ievent_source->list, &ctx->removed_event_sources);
 -      usbi_event_source_notification(ctx);
--      usbi_mutex_unlock(&ctx->event_data_lock);
-       free(ipollfd);
 -
 -#if !defined(PLATFORM_WINDOWS)
--      if (ctx->fd_removed_cb)
-               ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
 -              ctx->fd_removed_cb(os_handle, ctx->fd_cb_user_data);
 -#endif
--}
--
--/** \ingroup libusb_poll
-- * Retrieve a list of file descriptors that should be polled by your main loop
-- * as libusb event sources.
-- *
-- * The returned list is NULL-terminated and should be freed with libusb_free_pollfds()
-- * when done. The actual list contents must not be touched.
-- *
-- * As file descriptors are a Unix-specific concept, this function is not
-- * available on Windows and will always return NULL.
-- *
-- * \param ctx the context to operate on, or NULL for the default context
-- * \returns a NULL-terminated list of libusb_pollfd structures
-- * \returns NULL on error
-- * \returns NULL on platforms where the functionality is not available
-- */
--DEFAULT_VISIBILITY
--const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
--      libusb_context *ctx)
--{
- #ifndef OS_WINDOWS
 -#if !defined(PLATFORM_WINDOWS)
--      struct libusb_pollfd **ret = NULL;
-       struct usbi_pollfd *ipollfd;
-       size_t i = 0;
-       USBI_GET_CONTEXT(ctx);
 -      struct usbi_event_source *ievent_source;
 -      size_t i;
 -
 -      static_assert(sizeof(struct usbi_event_source_data) == sizeof(struct libusb_pollfd),
 -                    "mismatch between usbi_event_source_data and libusb_pollfd sizes");
 -
 -      ctx = usbi_get_context(ctx);
--
--      usbi_mutex_lock(&ctx->event_data_lock);
--
-       ret = calloc(ctx->pollfds_cnt + 1, sizeof(struct libusb_pollfd *));
 -      i = 0;
 -      for_each_event_source(ctx, ievent_source)
 -              i++;
 -
 -      ret = calloc(i + 1, sizeof(struct libusb_pollfd *));
--      if (!ret)
--              goto out;
--
-       list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
-               ret[i++] = (struct libusb_pollfd *) ipollfd;
-       ret[ctx->pollfds_cnt] = NULL;
 -      i = 0;
 -      for_each_event_source(ctx, ievent_source)
 -              ret[i++] = (struct libusb_pollfd *)ievent_source;
--
--out:
--      usbi_mutex_unlock(&ctx->event_data_lock);
-       return (const struct libusb_pollfd **) ret;
 -      return (const struct libusb_pollfd **)ret;
--#else
-       usbi_err(ctx, "external polling of libusb's internal descriptors "\
-               "is not yet supported on Windows platforms");
 -      usbi_err(ctx, "external polling of libusb's internal event sources " \
 -              "is not yet supported on Windows");
--      return NULL;
--#endif
--}
--
--/** \ingroup libusb_poll
-- * Free a list of libusb_pollfd structures. This should be called for all
-- * pollfd lists allocated with libusb_get_pollfds().
-- *
-- * Since version 1.0.20, \ref LIBUSB_API_VERSION >= 0x01000104
-- *
-- * It is legal to call this function with a NULL pollfd list. In this case,
-  * the function will simply return safely.
 - * the function will simply do nothing.
-- *
-- * \param pollfds the list of libusb_pollfd structures to free
-- */
--void API_EXPORTED libusb_free_pollfds(const struct libusb_pollfd **pollfds)
--{
-       if (!pollfds)
-               return;
 -#if !defined(PLATFORM_WINDOWS)
--      free((void *)pollfds);
 -#else
 -      UNUSED(pollfds);
 -#endif
--}
--
--/* Backends may call this from handle_events to report disconnection of a
-- * device. This function ensures transfers get cancelled appropriately.
-- * Callers of this function must hold the events_lock.
-- */
--void usbi_handle_disconnect(struct libusb_device_handle *dev_handle)
--{
 -      struct libusb_context *ctx = HANDLE_CTX(dev_handle);
--      struct usbi_transfer *cur;
--      struct usbi_transfer *to_cancel;
--
--      usbi_dbg("device %d.%d",
--              dev_handle->dev->bus_number, dev_handle->dev->device_address);
--
--      /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
--       * status code.
--       *
--       * when we find a transfer for this device on the list, there are two
--       * possible scenarios:
--       * 1. the transfer is currently in-flight, in which case we terminate the
--       *    transfer here
--       * 2. the transfer has been added to the flying transfer list by
--       *    libusb_submit_transfer, has failed to submit and
--       *    libusb_submit_transfer is waiting for us to release the
--       *    flying_transfers_lock to remove it, so we ignore it
--       */
--
--      while (1) {
--              to_cancel = NULL;
-               usbi_mutex_lock(&HANDLE_CTX(dev_handle)->flying_transfers_lock);
-               list_for_each_entry(cur, &HANDLE_CTX(dev_handle)->flying_transfers, list, struct usbi_transfer)
 -              usbi_mutex_lock(&ctx->flying_transfers_lock);
 -              for_each_transfer(ctx, cur) {
--                      if (USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == dev_handle) {
--                              usbi_mutex_lock(&cur->lock);
--                              if (cur->state_flags & USBI_TRANSFER_IN_FLIGHT)
--                                      to_cancel = cur;
--                              usbi_mutex_unlock(&cur->lock);
--
--                              if (to_cancel)
--                                      break;
--                      }
-               usbi_mutex_unlock(&HANDLE_CTX(dev_handle)->flying_transfers_lock);
 -              }
 -              usbi_mutex_unlock(&ctx->flying_transfers_lock);
--
--              if (!to_cancel)
--                      break;
--
--              usbi_dbg("cancelling transfer %p from disconnect",
--                       USBI_TRANSFER_TO_LIBUSB_TRANSFER(to_cancel));
--
--              usbi_mutex_lock(&to_cancel->lock);
--              usbi_backend.clear_transfer_priv(to_cancel);
--              usbi_mutex_unlock(&to_cancel->lock);
--              usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);
--      }
--}
diff --cc mac/libusb/libusb.h
index 430136b2e28508f2c83292dd152709726d5b01a8,1308571cd60f352437baf4bcee267a5c01f7b3f6..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2039 -1,2113 +1,0 @@@
--/*
-- * Public libusb header file
-- * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
-- * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
-- * Copyright © 2012 Pete Batard <pete@akeo.ie>
-  * Copyright © 2012 Nathan Hjelm <hjelmn@cs.unm.edu>
 - * Copyright © 2012-2018 Nathan Hjelm <hjelmn@cs.unm.edu>
 - * Copyright © 2014-2020 Chris Dickens <christopher.a.dickens@gmail.com>
-- * For more information, please visit: http://libusb.info
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
--#ifndef LIBUSB_H
--#define LIBUSB_H
--
- #ifdef _MSC_VER
 -#if defined(_MSC_VER)
--/* on MS environments, the inline keyword is available in C++ only */
--#if !defined(__cplusplus)
--#define inline __inline
--#endif
- /* ssize_t is also not available (copy/paste from MinGW) */
- #ifndef _SSIZE_T_DEFINED
- #define _SSIZE_T_DEFINED
- #undef ssize_t
- #ifdef _WIN64
-   typedef __int64 ssize_t;
- #else
-   typedef int ssize_t;
- #endif /* _WIN64 */
- #endif /* _SSIZE_T_DEFINED */
 -/* ssize_t is also not available */
 -#include <basetsd.h>
 -typedef SSIZE_T ssize_t;
--#endif /* _MSC_VER */
--
- /* stdint.h is not available on older MSVC */
- #if defined(_MSC_VER) && (_MSC_VER < 1600) && (!defined(_STDINT)) && (!defined(_STDINT_H))
- typedef unsigned __int8   uint8_t;
- typedef unsigned __int16  uint16_t;
- typedef unsigned __int32  uint32_t;
- #else
 -#include <limits.h>
--#include <stdint.h>
- #endif
- #if !defined(_WIN32_WCE)
--#include <sys/types.h>
- #endif
- #if defined(__linux__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__HAIKU__)
 -#if !defined(_MSC_VER)
--#include <sys/time.h>
--#endif
--#include <time.h>
- #include <limits.h>
--
--#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
--#define ZERO_SIZED_ARRAY              /* [] - valid C99 code */
--#else
--#define ZERO_SIZED_ARRAY      0       /* [0] - non-standard, but usually working code */
- #endif
 -#endif /* __STDC_VERSION__ */
--
--/* 'interface' might be defined as a macro on Windows, so we need to
-- * undefine it so as not to break the current libusb API, because
-- * libusb_config_descriptor has an 'interface' member
-- * As this can be problematic if you include windows.h after libusb.h
-- * in your sources, we force windows.h to be included first. */
- #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
 -#if defined(_WIN32) || defined(__CYGWIN__)
--#include <windows.h>
--#if defined(interface)
--#undef interface
--#endif
--#if !defined(__CYGWIN__)
--#include <winsock.h>
- #endif
--#endif
 -#endif /* _WIN32 || __CYGWIN__ */
--
- #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
- #define LIBUSB_DEPRECATED_FOR(f) \
-   __attribute__((deprecated("Use " #f " instead")))
- #elif __GNUC__ >= 3
- #define LIBUSB_DEPRECATED_FOR(f) __attribute__((deprecated))
 -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
 -#define LIBUSB_DEPRECATED_FOR(f) __attribute__ ((deprecated ("Use " #f " instead")))
 -#elif defined(__GNUC__) && (__GNUC__ >= 3)
 -#define LIBUSB_DEPRECATED_FOR(f) __attribute__ ((deprecated))
--#else
--#define LIBUSB_DEPRECATED_FOR(f)
 -#endif /* __GNUC__ */
 -
 -#if defined(__GNUC__)
 -#define LIBUSB_PACKED __attribute__ ((packed))
 -#else
 -#define LIBUSB_PACKED
--#endif /* __GNUC__ */
--
--/** \def LIBUSB_CALL
-- * \ingroup libusb_misc
-- * libusb's Windows calling convention.
-- *
-- * Under Windows, the selection of available compilers and configurations
-- * means that, unlike other platforms, there is not <em>one true calling
-- * convention</em> (calling convention: the manner in which parameters are
-- * passed to functions in the generated assembly code).
-- *
-- * Matching the Windows API itself, libusb uses the WINAPI convention (which
-- * translates to the <tt>stdcall</tt> convention) and guarantees that the
-- * library is compiled in this way. The public header file also includes
-- * appropriate annotations so that your own software will use the right
-- * convention, even if another convention is being used by default within
-- * your codebase.
-- *
-- * The one consideration that you must apply in your software is to mark
-- * all functions which you use as libusb callbacks with this LIBUSB_CALL
-- * annotation, so that they too get compiled for the correct calling
-- * convention.
-- *
-- * On non-Windows operating systems, this macro is defined as nothing. This
-- * means that you can apply it to your code without worrying about
-- * cross-platform compatibility.
-- */
--/* LIBUSB_CALL must be defined on both definition and declaration of libusb
-- * functions. You'd think that declaration would be enough, but cygwin will
-- * complain about conflicting types unless both are marked this way.
-- * The placement of this macro is important too; it must appear after the
-- * return type, before the function name. See internal documentation for
-- * API_EXPORTED.
-- */
- #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
 -#if defined(_WIN32) || defined(__CYGWIN__)
--#define LIBUSB_CALL WINAPI
--#else
--#define LIBUSB_CALL
- #endif
 -#endif /* _WIN32 || __CYGWIN__ */
--
--/** \def LIBUSB_API_VERSION
-- * \ingroup libusb_misc
-- * libusb's API version.
-- *
-- * Since version 1.0.13, to help with feature detection, libusb defines
-- * a LIBUSB_API_VERSION macro that gets increased every time there is a
-- * significant change to the API, such as the introduction of a new call,
-- * the definition of a new macro/enum member, or any other element that
-- * libusb applications may want to detect at compilation time.
-- *
-- * The macro is typically used in an application as follows:
-- * \code
-- * #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01001234)
-- * // Use one of the newer features from the libusb API
-- * #endif
-- * \endcode
-- *
-- * Internally, LIBUSB_API_VERSION is defined as follows:
-- * (libusb major << 24) | (libusb minor << 16) | (16 bit incremental)
-- */
- #define LIBUSB_API_VERSION 0x01000106
 -#define LIBUSB_API_VERSION 0x01000108
--
--/* The following is kept for compatibility, but will be deprecated in the future */
--#define LIBUSBX_API_VERSION LIBUSB_API_VERSION
--
- #ifdef __cplusplus
 -#if defined(__cplusplus)
--extern "C" {
--#endif
--
--/**
-- * \ingroup libusb_misc
-- * Convert a 16-bit value from host-endian to little-endian format. On
-- * little endian systems, this function does nothing. On big endian systems,
-- * the bytes are swapped.
-- * \param x the host-endian value to convert
-- * \returns the value in little-endian byte order
-- */
--static inline uint16_t libusb_cpu_to_le16(const uint16_t x)
--{
--      union {
--              uint8_t  b8[2];
--              uint16_t b16;
--      } _tmp;
--      _tmp.b8[1] = (uint8_t) (x >> 8);
--      _tmp.b8[0] = (uint8_t) (x & 0xff);
--      return _tmp.b16;
--}
--
--/** \def libusb_le16_to_cpu
-- * \ingroup libusb_misc
-- * Convert a 16-bit value from little-endian to host-endian format. On
-- * little endian systems, this function does nothing. On big endian systems,
-- * the bytes are swapped.
-- * \param x the little-endian value to convert
-- * \returns the value in host-endian byte order
-- */
--#define libusb_le16_to_cpu libusb_cpu_to_le16
--
--/* standard USB stuff */
--
--/** \ingroup libusb_desc
-- * Device and/or Interface Class codes */
--enum libusb_class_code {
--      /** In the context of a \ref libusb_device_descriptor "device descriptor",
--       * this bDeviceClass value indicates that each interface specifies its
--       * own class information and all interfaces operate independently.
--       */
-       LIBUSB_CLASS_PER_INTERFACE = 0,
 -      LIBUSB_CLASS_PER_INTERFACE = 0x00,
--
--      /** Audio class */
-       LIBUSB_CLASS_AUDIO = 1,
 -      LIBUSB_CLASS_AUDIO = 0x01,
--
--      /** Communications class */
-       LIBUSB_CLASS_COMM = 2,
 -      LIBUSB_CLASS_COMM = 0x02,
--
--      /** Human Interface Device class */
-       LIBUSB_CLASS_HID = 3,
 -      LIBUSB_CLASS_HID = 0x03,
--
--      /** Physical */
-       LIBUSB_CLASS_PHYSICAL = 5,
-       /** Printer class */
-       LIBUSB_CLASS_PRINTER = 7,
 -      LIBUSB_CLASS_PHYSICAL = 0x05,
--
--      /** Image class */
-       LIBUSB_CLASS_PTP = 6, /* legacy name from libusb-0.1 usb.h */
-       LIBUSB_CLASS_IMAGE = 6,
 -      LIBUSB_CLASS_IMAGE = 0x06,
 -      LIBUSB_CLASS_PTP = 0x06, /* legacy name from libusb-0.1 usb.h */
 -
 -      /** Printer class */
 -      LIBUSB_CLASS_PRINTER = 0x07,
--
--      /** Mass storage class */
-       LIBUSB_CLASS_MASS_STORAGE = 8,
 -      LIBUSB_CLASS_MASS_STORAGE = 0x08,
--
--      /** Hub class */
-       LIBUSB_CLASS_HUB = 9,
 -      LIBUSB_CLASS_HUB = 0x09,
--
--      /** Data class */
-       LIBUSB_CLASS_DATA = 10,
 -      LIBUSB_CLASS_DATA = 0x0a,
--
--      /** Smart Card */
--      LIBUSB_CLASS_SMART_CARD = 0x0b,
--
--      /** Content Security */
--      LIBUSB_CLASS_CONTENT_SECURITY = 0x0d,
--
--      /** Video */
--      LIBUSB_CLASS_VIDEO = 0x0e,
--
--      /** Personal Healthcare */
--      LIBUSB_CLASS_PERSONAL_HEALTHCARE = 0x0f,
--
--      /** Diagnostic Device */
--      LIBUSB_CLASS_DIAGNOSTIC_DEVICE = 0xdc,
--
--      /** Wireless class */
--      LIBUSB_CLASS_WIRELESS = 0xe0,
 -
 -      /** Miscellaneous class */
 -      LIBUSB_CLASS_MISCELLANEOUS = 0xef,
--
--      /** Application class */
--      LIBUSB_CLASS_APPLICATION = 0xfe,
--
--      /** Class is vendor-specific */
--      LIBUSB_CLASS_VENDOR_SPEC = 0xff
--};
--
--/** \ingroup libusb_desc
-- * Descriptor types as defined by the USB specification. */
--enum libusb_descriptor_type {
--      /** Device descriptor. See libusb_device_descriptor. */
--      LIBUSB_DT_DEVICE = 0x01,
--
--      /** Configuration descriptor. See libusb_config_descriptor. */
--      LIBUSB_DT_CONFIG = 0x02,
--
--      /** String descriptor */
--      LIBUSB_DT_STRING = 0x03,
--
--      /** Interface descriptor. See libusb_interface_descriptor. */
--      LIBUSB_DT_INTERFACE = 0x04,
--
--      /** Endpoint descriptor. See libusb_endpoint_descriptor. */
--      LIBUSB_DT_ENDPOINT = 0x05,
--
--      /** BOS descriptor */
--      LIBUSB_DT_BOS = 0x0f,
--
--      /** Device Capability descriptor */
--      LIBUSB_DT_DEVICE_CAPABILITY = 0x10,
--
--      /** HID descriptor */
--      LIBUSB_DT_HID = 0x21,
--
--      /** HID report descriptor */
--      LIBUSB_DT_REPORT = 0x22,
--
--      /** Physical descriptor */
--      LIBUSB_DT_PHYSICAL = 0x23,
--
--      /** Hub descriptor */
--      LIBUSB_DT_HUB = 0x29,
--
--      /** SuperSpeed Hub descriptor */
--      LIBUSB_DT_SUPERSPEED_HUB = 0x2a,
--
--      /** SuperSpeed Endpoint Companion descriptor */
--      LIBUSB_DT_SS_ENDPOINT_COMPANION = 0x30
--};
--
--/* Descriptor sizes per descriptor type */
--#define LIBUSB_DT_DEVICE_SIZE                 18
--#define LIBUSB_DT_CONFIG_SIZE                 9
--#define LIBUSB_DT_INTERFACE_SIZE              9
--#define LIBUSB_DT_ENDPOINT_SIZE                       7
--#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE         9       /* Audio extension */
--#define LIBUSB_DT_HUB_NONVAR_SIZE             7
--#define LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE  6
--#define LIBUSB_DT_BOS_SIZE                    5
--#define LIBUSB_DT_DEVICE_CAPABILITY_SIZE      3
--
--/* BOS descriptor sizes */
--#define LIBUSB_BT_USB_2_0_EXTENSION_SIZE      7
--#define LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE       10
--#define LIBUSB_BT_CONTAINER_ID_SIZE           20
--
--/* We unwrap the BOS => define its max size */
- #define LIBUSB_DT_BOS_MAX_SIZE                ((LIBUSB_DT_BOS_SIZE)     +\
-                                       (LIBUSB_BT_USB_2_0_EXTENSION_SIZE)       +\
-                                       (LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) +\
-                                       (LIBUSB_BT_CONTAINER_ID_SIZE))
 -#define LIBUSB_DT_BOS_MAX_SIZE                                \
 -      (LIBUSB_DT_BOS_SIZE +                           \
 -       LIBUSB_BT_USB_2_0_EXTENSION_SIZE +             \
 -       LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE +      \
 -       LIBUSB_BT_CONTAINER_ID_SIZE)
--
- #define LIBUSB_ENDPOINT_ADDRESS_MASK  0x0f    /* in bEndpointAddress */
 -#define LIBUSB_ENDPOINT_ADDRESS_MASK          0x0f    /* in bEndpointAddress */
--#define LIBUSB_ENDPOINT_DIR_MASK              0x80
--
--/** \ingroup libusb_desc
-- * Endpoint direction. Values for bit 7 of the
-- * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme.
-- */
--enum libusb_endpoint_direction {
-       /** In: device-to-host */
-       LIBUSB_ENDPOINT_IN = 0x80,
--      /** Out: host-to-device */
-       LIBUSB_ENDPOINT_OUT = 0x00
 -      LIBUSB_ENDPOINT_OUT = 0x00,
 -
 -      /** In: device-to-host */
 -      LIBUSB_ENDPOINT_IN = 0x80
--};
--
- #define LIBUSB_TRANSFER_TYPE_MASK                     0x03    /* in bmAttributes */
 -#define LIBUSB_TRANSFER_TYPE_MASK             0x03    /* in bmAttributes */
--
--/** \ingroup libusb_desc
-- * Endpoint transfer type. Values for bits 0:1 of the
-- * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field.
-- */
- enum libusb_transfer_type {
 -enum libusb_endpoint_transfer_type {
--      /** Control endpoint */
-       LIBUSB_TRANSFER_TYPE_CONTROL = 0,
 -      LIBUSB_ENDPOINT_TRANSFER_TYPE_CONTROL = 0x0,
--
--      /** Isochronous endpoint */
-       LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1,
 -      LIBUSB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS = 0x1,
--
--      /** Bulk endpoint */
-       LIBUSB_TRANSFER_TYPE_BULK = 2,
 -      LIBUSB_ENDPOINT_TRANSFER_TYPE_BULK = 0x2,
--
--      /** Interrupt endpoint */
-       LIBUSB_TRANSFER_TYPE_INTERRUPT = 3,
-       /** Stream endpoint */
-       LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4,
 -      LIBUSB_ENDPOINT_TRANSFER_TYPE_INTERRUPT = 0x3
--};
--
--/** \ingroup libusb_misc
-- * Standard requests, as defined in table 9-5 of the USB 3.0 specifications */
--enum libusb_standard_request {
--      /** Request status of the specific recipient */
--      LIBUSB_REQUEST_GET_STATUS = 0x00,
--
--      /** Clear or disable a specific feature */
--      LIBUSB_REQUEST_CLEAR_FEATURE = 0x01,
--
--      /* 0x02 is reserved */
--
--      /** Set or enable a specific feature */
--      LIBUSB_REQUEST_SET_FEATURE = 0x03,
--
--      /* 0x04 is reserved */
--
--      /** Set device address for all future accesses */
--      LIBUSB_REQUEST_SET_ADDRESS = 0x05,
--
--      /** Get the specified descriptor */
--      LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06,
--
--      /** Used to update existing descriptors or add new descriptors */
--      LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07,
--
--      /** Get the current device configuration value */
--      LIBUSB_REQUEST_GET_CONFIGURATION = 0x08,
--
--      /** Set device configuration */
--      LIBUSB_REQUEST_SET_CONFIGURATION = 0x09,
--
--      /** Return the selected alternate setting for the specified interface */
-       LIBUSB_REQUEST_GET_INTERFACE = 0x0A,
 -      LIBUSB_REQUEST_GET_INTERFACE = 0x0a,
--
--      /** Select an alternate interface for the specified interface */
-       LIBUSB_REQUEST_SET_INTERFACE = 0x0B,
 -      LIBUSB_REQUEST_SET_INTERFACE = 0x0b,
--
--      /** Set then report an endpoint's synchronization frame */
-       LIBUSB_REQUEST_SYNCH_FRAME = 0x0C,
 -      LIBUSB_REQUEST_SYNCH_FRAME = 0x0c,
--
--      /** Sets both the U1 and U2 Exit Latency */
--      LIBUSB_REQUEST_SET_SEL = 0x30,
--
--      /** Delay from the time a host transmits a packet to the time it is
--        * received by the device. */
-       LIBUSB_SET_ISOCH_DELAY = 0x31,
 -      LIBUSB_SET_ISOCH_DELAY = 0x31
--};
--
--/** \ingroup libusb_misc
-- * Request type bits of the
-- * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
-- * transfers. */
--enum libusb_request_type {
--      /** Standard */
--      LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5),
--
--      /** Class */
--      LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5),
--
--      /** Vendor */
--      LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5),
--
--      /** Reserved */
--      LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5)
--};
--
--/** \ingroup libusb_misc
-- * Recipient bits of the
-- * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
-- * transfers. Values 4 through 31 are reserved. */
--enum libusb_request_recipient {
--      /** Device */
--      LIBUSB_RECIPIENT_DEVICE = 0x00,
--
--      /** Interface */
--      LIBUSB_RECIPIENT_INTERFACE = 0x01,
--
--      /** Endpoint */
--      LIBUSB_RECIPIENT_ENDPOINT = 0x02,
--
--      /** Other */
-       LIBUSB_RECIPIENT_OTHER = 0x03,
 -      LIBUSB_RECIPIENT_OTHER = 0x03
--};
--
- #define LIBUSB_ISO_SYNC_TYPE_MASK             0x0C
 -#define LIBUSB_ISO_SYNC_TYPE_MASK     0x0c
--
--/** \ingroup libusb_desc
-- * Synchronization type for isochronous endpoints. Values for bits 2:3 of the
-- * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
-- * libusb_endpoint_descriptor.
-- */
--enum libusb_iso_sync_type {
--      /** No synchronization */
-       LIBUSB_ISO_SYNC_TYPE_NONE = 0,
 -      LIBUSB_ISO_SYNC_TYPE_NONE = 0x0,
--
--      /** Asynchronous */
-       LIBUSB_ISO_SYNC_TYPE_ASYNC = 1,
 -      LIBUSB_ISO_SYNC_TYPE_ASYNC = 0x1,
--
--      /** Adaptive */
-       LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2,
 -      LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 0x2,
--
--      /** Synchronous */
-       LIBUSB_ISO_SYNC_TYPE_SYNC = 3
 -      LIBUSB_ISO_SYNC_TYPE_SYNC = 0x3
--};
--
- #define LIBUSB_ISO_USAGE_TYPE_MASK 0x30
 -#define LIBUSB_ISO_USAGE_TYPE_MASK    0x30
--
--/** \ingroup libusb_desc
-- * Usage type for isochronous endpoints. Values for bits 4:5 of the
-- * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
-- * libusb_endpoint_descriptor.
-- */
--enum libusb_iso_usage_type {
--      /** Data endpoint */
-       LIBUSB_ISO_USAGE_TYPE_DATA = 0,
 -      LIBUSB_ISO_USAGE_TYPE_DATA = 0x0,
--
--      /** Feedback endpoint */
-       LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1,
 -      LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 0x1,
--
--      /** Implicit feedback Data endpoint */
-       LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2,
 -      LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 0x2
 -};
 -
 -/** \ingroup libusb_desc
 - * Supported speeds (wSpeedSupported) bitfield. Indicates what
 - * speeds the device supports.
 - */
 -enum libusb_supported_speed {
 -      /** Low speed operation supported (1.5MBit/s). */
 -      LIBUSB_LOW_SPEED_OPERATION = (1 << 0),
 -
 -      /** Full speed operation supported (12MBit/s). */
 -      LIBUSB_FULL_SPEED_OPERATION = (1 << 1),
 -
 -      /** High speed operation supported (480MBit/s). */
 -      LIBUSB_HIGH_SPEED_OPERATION = (1 << 2),
 -
 -      /** Superspeed operation supported (5000MBit/s). */
 -      LIBUSB_SUPER_SPEED_OPERATION = (1 << 3)
 -};
 -
 -/** \ingroup libusb_desc
 - * Masks for the bits of the
 - * \ref libusb_usb_2_0_extension_descriptor::bmAttributes "bmAttributes" field
 - * of the USB 2.0 Extension descriptor.
 - */
 -enum libusb_usb_2_0_extension_attributes {
 -      /** Supports Link Power Management (LPM) */
 -      LIBUSB_BM_LPM_SUPPORT = (1 << 1)
 -};
 -
 -/** \ingroup libusb_desc
 - * Masks for the bits of the
 - * \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field
 - * field of the SuperSpeed USB Device Capability descriptor.
 - */
 -enum libusb_ss_usb_device_capability_attributes {
 -      /** Supports Latency Tolerance Messages (LTM) */
 -      LIBUSB_BM_LTM_SUPPORT = (1 << 1)
 -};
 -
 -/** \ingroup libusb_desc
 - * USB capability types
 - */
 -enum libusb_bos_type {
 -      /** Wireless USB device capability */
 -      LIBUSB_BT_WIRELESS_USB_DEVICE_CAPABILITY = 0x01,
 -
 -      /** USB 2.0 extensions */
 -      LIBUSB_BT_USB_2_0_EXTENSION = 0x02,
 -
 -      /** SuperSpeed USB device capability */
 -      LIBUSB_BT_SS_USB_DEVICE_CAPABILITY = 0x03,
 -
 -      /** Container ID type */
 -      LIBUSB_BT_CONTAINER_ID = 0x04
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the standard USB device descriptor. This
-- * descriptor is documented in section 9.6.1 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_device_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this
--       * context. */
--      uint8_t  bDescriptorType;
--
--      /** USB specification release number in binary-coded decimal. A value of
--       * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */
--      uint16_t bcdUSB;
--
--      /** USB-IF class code for the device. See \ref libusb_class_code. */
--      uint8_t  bDeviceClass;
--
--      /** USB-IF subclass code for the device, qualified by the bDeviceClass
--       * value */
--      uint8_t  bDeviceSubClass;
--
--      /** USB-IF protocol code for the device, qualified by the bDeviceClass and
--       * bDeviceSubClass values */
--      uint8_t  bDeviceProtocol;
--
--      /** Maximum packet size for endpoint 0 */
--      uint8_t  bMaxPacketSize0;
--
--      /** USB-IF vendor ID */
--      uint16_t idVendor;
--
--      /** USB-IF product ID */
--      uint16_t idProduct;
--
--      /** Device release number in binary-coded decimal */
--      uint16_t bcdDevice;
--
--      /** Index of string descriptor describing manufacturer */
--      uint8_t  iManufacturer;
--
--      /** Index of string descriptor describing product */
--      uint8_t  iProduct;
--
--      /** Index of string descriptor containing device serial number */
--      uint8_t  iSerialNumber;
--
--      /** Number of possible configurations */
--      uint8_t  bNumConfigurations;
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the standard USB endpoint descriptor. This
-- * descriptor is documented in section 9.6.6 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_endpoint_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in
--       * this context. */
--      uint8_t  bDescriptorType;
--
--      /** The address of the endpoint described by this descriptor. Bits 0:3 are
--       * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction,
-        * see \ref libusb_endpoint_direction.
-        */
 -       * see \ref libusb_endpoint_direction. */
--      uint8_t  bEndpointAddress;
--
--      /** Attributes which apply to the endpoint when it is configured using
--       * the bConfigurationValue. Bits 0:1 determine the transfer type and
-        * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for
-        * isochronous endpoints and correspond to \ref libusb_iso_sync_type.
 -       * correspond to \ref libusb_endpoint_transfer_type. Bits 2:3 are only used
 -       * for isochronous endpoints and correspond to \ref libusb_iso_sync_type.
--       * Bits 4:5 are also only used for isochronous endpoints and correspond to
-        * \ref libusb_iso_usage_type. Bits 6:7 are reserved.
-        */
 -       * \ref libusb_iso_usage_type. Bits 6:7 are reserved. */
--      uint8_t  bmAttributes;
--
--      /** Maximum packet size this endpoint is capable of sending/receiving. */
--      uint16_t wMaxPacketSize;
--
--      /** Interval for polling endpoint for data transfers. */
--      uint8_t  bInterval;
--
--      /** For audio devices only: the rate at which synchronization feedback
--       * is provided. */
--      uint8_t  bRefresh;
--
--      /** For audio devices only: the address if the synch endpoint */
--      uint8_t  bSynchAddress;
--
--      /** Extra descriptors. If libusb encounters unknown endpoint descriptors,
--       * it will store them here, should you wish to parse them. */
--      const unsigned char *extra;
--
-       /** Length of the extra descriptors, in bytes. */
 -      /** Length of the extra descriptors, in bytes. Must be non-negative. */
--      int extra_length;
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the standard USB interface descriptor. This
-- * descriptor is documented in section 9.6.5 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_interface_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE
--       * in this context. */
--      uint8_t  bDescriptorType;
--
--      /** Number of this interface */
--      uint8_t  bInterfaceNumber;
--
--      /** Value used to select this alternate setting for this interface */
--      uint8_t  bAlternateSetting;
--
--      /** Number of endpoints used by this interface (excluding the control
--       * endpoint). */
--      uint8_t  bNumEndpoints;
--
--      /** USB-IF class code for this interface. See \ref libusb_class_code. */
--      uint8_t  bInterfaceClass;
--
--      /** USB-IF subclass code for this interface, qualified by the
--       * bInterfaceClass value */
--      uint8_t  bInterfaceSubClass;
--
--      /** USB-IF protocol code for this interface, qualified by the
--       * bInterfaceClass and bInterfaceSubClass values */
--      uint8_t  bInterfaceProtocol;
--
--      /** Index of string descriptor describing this interface */
--      uint8_t  iInterface;
--
--      /** Array of endpoint descriptors. This length of this array is determined
--       * by the bNumEndpoints field. */
--      const struct libusb_endpoint_descriptor *endpoint;
--
--      /** Extra descriptors. If libusb encounters unknown interface descriptors,
--       * it will store them here, should you wish to parse them. */
--      const unsigned char *extra;
--
-       /** Length of the extra descriptors, in bytes. */
 -      /** Length of the extra descriptors, in bytes. Must be non-negative. */
--      int extra_length;
--};
--
--/** \ingroup libusb_desc
-- * A collection of alternate settings for a particular USB interface.
-- */
--struct libusb_interface {
--      /** Array of interface descriptors. The length of this array is determined
--       * by the num_altsetting field. */
--      const struct libusb_interface_descriptor *altsetting;
--
-       /** The number of alternate settings that belong to this interface */
 -      /** The number of alternate settings that belong to this interface.
 -       * Must be non-negative. */
--      int num_altsetting;
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the standard USB configuration descriptor. This
-- * descriptor is documented in section 9.6.3 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_config_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG
--       * in this context. */
--      uint8_t  bDescriptorType;
--
--      /** Total length of data returned for this configuration */
--      uint16_t wTotalLength;
--
--      /** Number of interfaces supported by this configuration */
--      uint8_t  bNumInterfaces;
--
--      /** Identifier value for this configuration */
--      uint8_t  bConfigurationValue;
--
--      /** Index of string descriptor describing this configuration */
--      uint8_t  iConfiguration;
--
--      /** Configuration characteristics */
--      uint8_t  bmAttributes;
--
--      /** Maximum power consumption of the USB device from this bus in this
--       * configuration when the device is fully operation. Expressed in units
--       * of 2 mA when the device is operating in high-speed mode and in units
--       * of 8 mA when the device is operating in super-speed mode. */
--      uint8_t  MaxPower;
--
--      /** Array of interfaces supported by this configuration. The length of
--       * this array is determined by the bNumInterfaces field. */
--      const struct libusb_interface *interface;
--
--      /** Extra descriptors. If libusb encounters unknown configuration
--       * descriptors, it will store them here, should you wish to parse them. */
--      const unsigned char *extra;
--
-       /** Length of the extra descriptors, in bytes. */
 -      /** Length of the extra descriptors, in bytes. Must be non-negative. */
--      int extra_length;
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the superspeed endpoint companion
-- * descriptor. This descriptor is documented in section 9.6.7 of
-- * the USB 3.0 specification. All multiple-byte fields are represented in
-- * host-endian format.
-- */
--struct libusb_ss_endpoint_companion_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_SS_ENDPOINT_COMPANION in
--       * this context. */
--      uint8_t  bDescriptorType;
--
--      /** The maximum number of packets the endpoint can send or
--       *  receive as part of a burst. */
--      uint8_t  bMaxBurst;
--
-       /** In bulk EP: bits 4:0 represents the maximum number of
-        *  streams the EP supports. In isochronous EP: bits 1:0
-        *  represents the Mult - a zero based value that determines
-        *  the maximum number of packets within a service interval  */
 -      /** In bulk EP: bits 4:0 represents the maximum number of
 -       *  streams the EP supports. In isochronous EP: bits 1:0
 -       *  represents the Mult - a zero based value that determines
 -       *  the maximum number of packets within a service interval  */
--      uint8_t  bmAttributes;
--
-       /** The total number of bytes this EP will transfer every
-        *  service interval. valid only for periodic EPs. */
 -      /** The total number of bytes this EP will transfer every
 -       *  service interval. Valid only for periodic EPs. */
--      uint16_t wBytesPerInterval;
--};
--
--/** \ingroup libusb_desc
-- * A generic representation of a BOS Device Capability descriptor. It is
-- * advised to check bDevCapabilityType and call the matching
-- * libusb_get_*_descriptor function to get a structure fully matching the type.
-- */
--struct libusb_bos_dev_capability_descriptor {
--      /** Size of this descriptor (in bytes) */
-       uint8_t bLength;
 -      uint8_t  bLength;
 -
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
--       * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
-       uint8_t bDescriptorType;
 -      uint8_t  bDescriptorType;
 -
--      /** Device Capability type */
-       uint8_t bDevCapabilityType;
 -      uint8_t  bDevCapabilityType;
 -
--      /** Device Capability data (bLength - 3 bytes) */
-       uint8_t dev_capability_data[ZERO_SIZED_ARRAY];
 -      uint8_t  dev_capability_data[ZERO_SIZED_ARRAY];
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the Binary Device Object Store (BOS) descriptor.
-- * This descriptor is documented in section 9.6.2 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_bos_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_BOS LIBUSB_DT_BOS
--       * in this context. */
--      uint8_t  bDescriptorType;
--
--      /** Length of this descriptor and all of its sub descriptors */
--      uint16_t wTotalLength;
--
--      /** The number of separate device capability descriptors in
--       * the BOS */
--      uint8_t  bNumDeviceCaps;
--
--      /** bNumDeviceCap Device Capability Descriptors */
--      struct libusb_bos_dev_capability_descriptor *dev_capability[ZERO_SIZED_ARRAY];
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the USB 2.0 Extension descriptor
-- * This descriptor is documented in section 9.6.2.1 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_usb_2_0_extension_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
--       * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
--      uint8_t  bDescriptorType;
--
--      /** Capability type. Will have value
--       * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION
--       * LIBUSB_BT_USB_2_0_EXTENSION in this context. */
--      uint8_t  bDevCapabilityType;
--
--      /** Bitmap encoding of supported device level features.
--       * A value of one in a bit location indicates a feature is
--       * supported; a value of zero indicates it is not supported.
--       * See \ref libusb_usb_2_0_extension_attributes. */
-       uint32_t  bmAttributes;
 -      uint32_t bmAttributes;
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the SuperSpeed USB Device Capability descriptor
-- * This descriptor is documented in section 9.6.2.2 of the USB 3.0 specification.
-- * All multiple-byte fields are represented in host-endian format.
-- */
--struct libusb_ss_usb_device_capability_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
--       * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
--      uint8_t  bDescriptorType;
--
--      /** Capability type. Will have value
--       * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
--       * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY in this context. */
--      uint8_t  bDevCapabilityType;
--
--      /** Bitmap encoding of supported device level features.
--       * A value of one in a bit location indicates a feature is
--       * supported; a value of zero indicates it is not supported.
--       * See \ref libusb_ss_usb_device_capability_attributes. */
--      uint8_t  bmAttributes;
--
--      /** Bitmap encoding of the speed supported by this device when
--       * operating in SuperSpeed mode. See \ref libusb_supported_speed. */
--      uint16_t wSpeedSupported;
--
--      /** The lowest speed at which all the functionality supported
--       * by the device is available to the user. For example if the
--       * device supports all its functionality when connected at
--       * full speed and above then it sets this value to 1. */
--      uint8_t  bFunctionalitySupport;
--
--      /** U1 Device Exit Latency. */
--      uint8_t  bU1DevExitLat;
--
--      /** U2 Device Exit Latency. */
--      uint16_t bU2DevExitLat;
--};
--
--/** \ingroup libusb_desc
-- * A structure representing the Container ID descriptor.
-- * This descriptor is documented in section 9.6.2.3 of the USB 3.0 specification.
-- * All multiple-byte fields, except UUIDs, are represented in host-endian format.
-- */
--struct libusb_container_id_descriptor {
--      /** Size of this descriptor (in bytes) */
--      uint8_t  bLength;
--
--      /** Descriptor type. Will have value
--       * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
--       * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
--      uint8_t  bDescriptorType;
--
--      /** Capability type. Will have value
--       * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID
--       * LIBUSB_BT_CONTAINER_ID in this context. */
--      uint8_t  bDevCapabilityType;
--
--      /** Reserved field */
-       uint8_t bReserved;
 -      uint8_t  bReserved;
--
--      /** 128 bit UUID */
--      uint8_t  ContainerID[16];
--};
--
--/** \ingroup libusb_asyncio
-- * Setup packet for control transfers. */
 -#if defined(_MSC_VER)
 -#pragma pack(push, 1)
 -#endif
--struct libusb_control_setup {
--      /** Request type. Bits 0:4 determine recipient, see
--       * \ref libusb_request_recipient. Bits 5:6 determine type, see
--       * \ref libusb_request_type. Bit 7 determines data transfer direction, see
--       * \ref libusb_endpoint_direction.
--       */
--      uint8_t  bmRequestType;
--
--      /** Request. If the type bits of bmRequestType are equal to
--       * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD
--       * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to
--       * \ref libusb_standard_request. For other cases, use of this field is
--       * application-specific. */
--      uint8_t  bRequest;
--
--      /** Value. Varies according to request */
--      uint16_t wValue;
--
--      /** Index. Varies according to request, typically used to pass an index
--       * or offset */
--      uint16_t wIndex;
--
--      /** Number of bytes to transfer */
--      uint16_t wLength;
- };
 -} LIBUSB_PACKED;
 -#if defined(_MSC_VER)
 -#pragma pack(pop)
 -#endif
--
--#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup))
--
--/* libusb */
--
--struct libusb_context;
--struct libusb_device;
--struct libusb_device_handle;
--
--/** \ingroup libusb_lib
-- * Structure providing the version of the libusb runtime
-- */
--struct libusb_version {
--      /** Library major version. */
--      const uint16_t major;
--
--      /** Library minor version. */
--      const uint16_t minor;
--
--      /** Library micro version. */
--      const uint16_t micro;
--
--      /** Library nano version. */
--      const uint16_t nano;
--
--      /** Library release candidate suffix string, e.g. "-rc4". */
--      const char *rc;
--
--      /** For ABI compatibility only. */
-       const char* describe;
 -      const char *describe;
--};
--
--/** \ingroup libusb_lib
-- * Structure representing a libusb session. The concept of individual libusb
-- * sessions allows for your program to use two libraries (or dynamically
-- * load two modules) which both independently use libusb. This will prevent
-- * interference between the individual libusb users - for example
-- * libusb_set_option() will not affect the other user of the library, and
-- * libusb_exit() will not destroy resources that the other user is still
-- * using.
-- *
-- * Sessions are created by libusb_init() and destroyed through libusb_exit().
-- * If your application is guaranteed to only ever include a single libusb
-- * user (i.e. you), you do not have to worry about contexts: pass NULL in
-- * every function call where a context is required. The default context
-- * will be used.
-- *
-- * For more information, see \ref libusb_contexts.
-- */
--typedef struct libusb_context libusb_context;
--
--/** \ingroup libusb_dev
-- * Structure representing a USB device detected on the system. This is an
-- * opaque type for which you are only ever provided with a pointer, usually
-- * originating from libusb_get_device_list().
-- *
-- * Certain operations can be performed on a device, but in order to do any
-- * I/O you will have to first obtain a device handle using libusb_open().
-- *
-- * Devices are reference counted with libusb_ref_device() and
-- * libusb_unref_device(), and are freed when the reference count reaches 0.
-- * New devices presented by libusb_get_device_list() have a reference count of
-- * 1, and libusb_free_device_list() can optionally decrease the reference count
-- * on all devices in the list. libusb_open() adds another reference which is
-- * later destroyed by libusb_close().
-- */
--typedef struct libusb_device libusb_device;
--
--
--/** \ingroup libusb_dev
-- * Structure representing a handle on a USB device. This is an opaque type for
-- * which you are only ever provided with a pointer, usually originating from
-- * libusb_open().
-- *
-- * A device handle is used to perform I/O and other operations. When finished
-- * with a device handle, you should call libusb_close().
-- */
--typedef struct libusb_device_handle libusb_device_handle;
--
--/** \ingroup libusb_dev
-- * Speed codes. Indicates the speed at which the device is operating.
-- */
--enum libusb_speed {
--      /** The OS doesn't report or know the device speed. */
--      LIBUSB_SPEED_UNKNOWN = 0,
--
--      /** The device is operating at low speed (1.5MBit/s). */
--      LIBUSB_SPEED_LOW = 1,
--
--      /** The device is operating at full speed (12MBit/s). */
--      LIBUSB_SPEED_FULL = 2,
--
--      /** The device is operating at high speed (480MBit/s). */
--      LIBUSB_SPEED_HIGH = 3,
--
--      /** The device is operating at super speed (5000MBit/s). */
--      LIBUSB_SPEED_SUPER = 4,
--
--      /** The device is operating at super speed plus (10000MBit/s). */
-       LIBUSB_SPEED_SUPER_PLUS = 5,
- };
- /** \ingroup libusb_dev
-  * Supported speeds (wSpeedSupported) bitfield. Indicates what
-  * speeds the device supports.
-  */
- enum libusb_supported_speed {
-       /** Low speed operation supported (1.5MBit/s). */
-       LIBUSB_LOW_SPEED_OPERATION   = 1,
-       /** Full speed operation supported (12MBit/s). */
-       LIBUSB_FULL_SPEED_OPERATION  = 2,
-       /** High speed operation supported (480MBit/s). */
-       LIBUSB_HIGH_SPEED_OPERATION  = 4,
-       /** Superspeed operation supported (5000MBit/s). */
-       LIBUSB_SUPER_SPEED_OPERATION = 8,
- };
- /** \ingroup libusb_dev
-  * Masks for the bits of the
-  * \ref libusb_usb_2_0_extension_descriptor::bmAttributes "bmAttributes" field
-  * of the USB 2.0 Extension descriptor.
-  */
- enum libusb_usb_2_0_extension_attributes {
-       /** Supports Link Power Management (LPM) */
-       LIBUSB_BM_LPM_SUPPORT = 2,
- };
- /** \ingroup libusb_dev
-  * Masks for the bits of the
-  * \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field
-  * field of the SuperSpeed USB Device Capability descriptor.
-  */
- enum libusb_ss_usb_device_capability_attributes {
-       /** Supports Latency Tolerance Messages (LTM) */
-       LIBUSB_BM_LTM_SUPPORT = 2,
- };
- /** \ingroup libusb_dev
-  * USB capability types
-  */
- enum libusb_bos_type {
-       /** Wireless USB device capability */
-       LIBUSB_BT_WIRELESS_USB_DEVICE_CAPABILITY        = 1,
-       /** USB 2.0 extensions */
-       LIBUSB_BT_USB_2_0_EXTENSION                     = 2,
-       /** SuperSpeed USB device capability */
-       LIBUSB_BT_SS_USB_DEVICE_CAPABILITY              = 3,
-       /** Container ID type */
-       LIBUSB_BT_CONTAINER_ID                          = 4,
 -      LIBUSB_SPEED_SUPER_PLUS = 5
--};
--
--/** \ingroup libusb_misc
-- * Error codes. Most libusb functions return 0 on success or one of these
-- * codes on failure.
-- * You can call libusb_error_name() to retrieve a string representation of an
-- * error code or libusb_strerror() to get an end-user suitable description of
-- * an error code.
-- */
--enum libusb_error {
--      /** Success (no error) */
--      LIBUSB_SUCCESS = 0,
--
--      /** Input/output error */
--      LIBUSB_ERROR_IO = -1,
--
--      /** Invalid parameter */
--      LIBUSB_ERROR_INVALID_PARAM = -2,
--
--      /** Access denied (insufficient permissions) */
--      LIBUSB_ERROR_ACCESS = -3,
--
--      /** No such device (it may have been disconnected) */
--      LIBUSB_ERROR_NO_DEVICE = -4,
--
--      /** Entity not found */
--      LIBUSB_ERROR_NOT_FOUND = -5,
--
--      /** Resource busy */
--      LIBUSB_ERROR_BUSY = -6,
--
--      /** Operation timed out */
--      LIBUSB_ERROR_TIMEOUT = -7,
--
--      /** Overflow */
--      LIBUSB_ERROR_OVERFLOW = -8,
--
--      /** Pipe error */
--      LIBUSB_ERROR_PIPE = -9,
--
--      /** System call interrupted (perhaps due to signal) */
--      LIBUSB_ERROR_INTERRUPTED = -10,
--
--      /** Insufficient memory */
--      LIBUSB_ERROR_NO_MEM = -11,
--
--      /** Operation not supported or unimplemented on this platform */
--      LIBUSB_ERROR_NOT_SUPPORTED = -12,
--
--      /* NB: Remember to update LIBUSB_ERROR_COUNT below as well as the
--         message strings in strerror.c when adding new error codes here. */
--
--      /** Other error */
-       LIBUSB_ERROR_OTHER = -99,
 -      LIBUSB_ERROR_OTHER = -99
--};
--
--/* Total number of error codes in enum libusb_error */
--#define LIBUSB_ERROR_COUNT 14
 -
 -/** \ingroup libusb_asyncio
 - * Transfer type */
 -enum libusb_transfer_type {
 -      /** Control transfer */
 -      LIBUSB_TRANSFER_TYPE_CONTROL = 0U,
 -
 -      /** Isochronous transfer */
 -      LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1U,
 -
 -      /** Bulk transfer */
 -      LIBUSB_TRANSFER_TYPE_BULK = 2U,
 -
 -      /** Interrupt transfer */
 -      LIBUSB_TRANSFER_TYPE_INTERRUPT = 3U,
 -
 -      /** Bulk stream transfer */
 -      LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4U
 -};
--
--/** \ingroup libusb_asyncio
-- * Transfer status codes */
--enum libusb_transfer_status {
--      /** Transfer completed without error. Note that this does not indicate
--       * that the entire amount of requested data was transferred. */
--      LIBUSB_TRANSFER_COMPLETED,
--
--      /** Transfer failed */
--      LIBUSB_TRANSFER_ERROR,
--
--      /** Transfer timed out */
--      LIBUSB_TRANSFER_TIMED_OUT,
--
--      /** Transfer was cancelled */
--      LIBUSB_TRANSFER_CANCELLED,
--
--      /** For bulk/interrupt endpoints: halt condition detected (endpoint
--       * stalled). For control endpoints: control request not supported. */
--      LIBUSB_TRANSFER_STALL,
--
--      /** Device was disconnected */
--      LIBUSB_TRANSFER_NO_DEVICE,
--
--      /** Device sent more data than requested */
-       LIBUSB_TRANSFER_OVERFLOW,
 -      LIBUSB_TRANSFER_OVERFLOW
--
--      /* NB! Remember to update libusb_error_name()
--         when adding new status codes here. */
--};
--
--/** \ingroup libusb_asyncio
-- * libusb_transfer.flags values */
--enum libusb_transfer_flags {
--      /** Report short frames as errors */
-       LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0,
 -      LIBUSB_TRANSFER_SHORT_NOT_OK = (1U << 0),
--
--      /** Automatically free() transfer buffer during libusb_free_transfer().
--       * Note that buffers allocated with libusb_dev_mem_alloc() should not
--       * be attempted freed in this way, since free() is not an appropriate
--       * way to release such memory. */
-       LIBUSB_TRANSFER_FREE_BUFFER = 1<<1,
 -      LIBUSB_TRANSFER_FREE_BUFFER = (1U << 1),
--
--      /** Automatically call libusb_free_transfer() after callback returns.
--       * If this flag is set, it is illegal to call libusb_free_transfer()
--       * from your transfer callback, as this will result in a double-free
--       * when this flag is acted upon. */
-       LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2,
 -      LIBUSB_TRANSFER_FREE_TRANSFER = (1U << 2),
--
--      /** Terminate transfers that are a multiple of the endpoint's
--       * wMaxPacketSize with an extra zero length packet. This is useful
--       * when a device protocol mandates that each logical request is
--       * terminated by an incomplete packet (i.e. the logical requests are
--       * not separated by other means).
--       *
--       * This flag only affects host-to-device transfers to bulk and interrupt
--       * endpoints. In other situations, it is ignored.
--       *
--       * This flag only affects transfers with a length that is a multiple of
--       * the endpoint's wMaxPacketSize. On transfers of other lengths, this
--       * flag has no effect. Therefore, if you are working with a device that
--       * needs a ZLP whenever the end of the logical request falls on a packet
--       * boundary, then it is sensible to set this flag on <em>every</em>
--       * transfer (you do not have to worry about only setting it on transfers
--       * that end on the boundary).
--       *
--       * This flag is currently only supported on Linux.
--       * On other systems, libusb_submit_transfer() will return
--       * LIBUSB_ERROR_NOT_SUPPORTED for every transfer where this flag is set.
--       *
--       * Available since libusb-1.0.9.
--       */
-       LIBUSB_TRANSFER_ADD_ZERO_PACKET = 1 << 3,
 -      LIBUSB_TRANSFER_ADD_ZERO_PACKET = (1U << 3)
--};
--
--/** \ingroup libusb_asyncio
-- * Isochronous packet descriptor. */
--struct libusb_iso_packet_descriptor {
--      /** Length of data to request in this packet */
--      unsigned int length;
--
--      /** Amount of data that was actually transferred */
--      unsigned int actual_length;
--
--      /** Status code for this packet */
--      enum libusb_transfer_status status;
--};
--
--struct libusb_transfer;
--
--/** \ingroup libusb_asyncio
-- * Asynchronous transfer callback function type. When submitting asynchronous
-- * transfers, you pass a pointer to a callback function of this type via the
-- * \ref libusb_transfer::callback "callback" member of the libusb_transfer
-- * structure. libusb will call this function later, when the transfer has
-- * completed or failed. See \ref libusb_asyncio for more information.
-- * \param transfer The libusb_transfer struct the callback function is being
-- * notified about.
-- */
--typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer);
--
--/** \ingroup libusb_asyncio
-- * The generic USB transfer structure. The user populates this structure and
-- * then submits it in order to request a transfer. After the transfer has
-- * completed, the library populates the transfer with the results and passes
-- * it back to the user.
-- */
--struct libusb_transfer {
--      /** Handle of the device that this transfer will be submitted to */
--      libusb_device_handle *dev_handle;
--
--      /** A bitwise OR combination of \ref libusb_transfer_flags. */
--      uint8_t flags;
--
--      /** Address of the endpoint where this transfer will be sent. */
--      unsigned char endpoint;
--
-       /** Type of the endpoint from \ref libusb_transfer_type */
 -      /** Type of the transfer from \ref libusb_transfer_type */
--      unsigned char type;
--
--      /** Timeout for this transfer in milliseconds. A value of 0 indicates no
--       * timeout. */
--      unsigned int timeout;
--
--      /** The status of the transfer. Read-only, and only for use within
--       * transfer callback function.
--       *
--       * If this is an isochronous transfer, this field may read COMPLETED even
--       * if there were errors in the frames. Use the
--       * \ref libusb_iso_packet_descriptor::status "status" field in each packet
--       * to determine if errors occurred. */
--      enum libusb_transfer_status status;
--
-       /** Length of the data buffer */
 -      /** Length of the data buffer. Must be non-negative. */
--      int length;
--
--      /** Actual length of data that was transferred. Read-only, and only for
--       * use within transfer callback function. Not valid for isochronous
--       * endpoint transfers. */
--      int actual_length;
--
--      /** Callback function. This will be invoked when the transfer completes,
--       * fails, or is cancelled. */
--      libusb_transfer_cb_fn callback;
--
-       /** User context data to pass to the callback function. */
 -      /** User context data. Useful for associating specific data to a transfer
 -       * that can be accessed from within the callback function.
 -       *
 -       * This field may be set manually or is taken as the `user_data` parameter
 -       * of the following functions:
 -       * - libusb_fill_bulk_transfer()
 -       * - libusb_fill_bulk_stream_transfer()
 -       * - libusb_fill_control_transfer()
 -       * - libusb_fill_interrupt_transfer()
 -       * - libusb_fill_iso_transfer() */
--      void *user_data;
--
--      /** Data buffer */
--      unsigned char *buffer;
--
--      /** Number of isochronous packets. Only used for I/O with isochronous
-        * endpoints. */
 -       * endpoints. Must be non-negative. */
--      int num_iso_packets;
--
--      /** Isochronous packet descriptors, for isochronous transfers only. */
--      struct libusb_iso_packet_descriptor iso_packet_desc[ZERO_SIZED_ARRAY];
--};
--
--/** \ingroup libusb_misc
-- * Capabilities supported by an instance of libusb on the current running
-- * platform. Test if the loaded library supports a given capability by calling
-- * \ref libusb_has_capability().
-- */
--enum libusb_capability {
--      /** The libusb_has_capability() API is available. */
-       LIBUSB_CAP_HAS_CAPABILITY = 0x0000,
 -      LIBUSB_CAP_HAS_CAPABILITY = 0x0000U,
 -
--      /** Hotplug support is available on this platform. */
-       LIBUSB_CAP_HAS_HOTPLUG = 0x0001,
 -      LIBUSB_CAP_HAS_HOTPLUG = 0x0001U,
 -
--      /** The library can access HID devices without requiring user intervention.
--       * Note that before being able to actually access an HID device, you may
--       * still have to call additional libusb functions such as
--       * \ref libusb_detach_kernel_driver(). */
-       LIBUSB_CAP_HAS_HID_ACCESS = 0x0100,
-       /** The library supports detaching of the default USB driver, using 
 -      LIBUSB_CAP_HAS_HID_ACCESS = 0x0100U,
 -
 -      /** The library supports detaching of the default USB driver, using
--       * \ref libusb_detach_kernel_driver(), if one is set by the OS kernel */
-       LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101
 -      LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101U
--};
--
--/** \ingroup libusb_lib
-- *  Log message levels.
-  *  - LIBUSB_LOG_LEVEL_NONE (0)    : no messages ever printed by the library (default)
-  *  - LIBUSB_LOG_LEVEL_ERROR (1)   : error messages are printed to stderr
-  *  - LIBUSB_LOG_LEVEL_WARNING (2) : warning and error messages are printed to stderr
-  *  - LIBUSB_LOG_LEVEL_INFO (3)    : informational messages are printed to stderr
-  *  - LIBUSB_LOG_LEVEL_DEBUG (4)   : debug and informational messages are printed to stderr
-- */
--enum libusb_log_level {
 -      /** (0) : No messages ever emitted by the library (default) */
--      LIBUSB_LOG_LEVEL_NONE = 0,
 -
 -      /** (1) : Error messages are emitted */
--      LIBUSB_LOG_LEVEL_ERROR = 1,
 -
 -      /** (2) : Warning and error messages are emitted */
--      LIBUSB_LOG_LEVEL_WARNING = 2,
 -
 -      /** (3) : Informational, warning and error messages are emitted */
--      LIBUSB_LOG_LEVEL_INFO = 3,
-       LIBUSB_LOG_LEVEL_DEBUG = 4,
 -
 -      /** (4) : All messages are emitted */
 -      LIBUSB_LOG_LEVEL_DEBUG = 4
 -};
 -
 -/** \ingroup libusb_lib
 - *  Log callback mode.
 - * \see libusb_set_log_cb()
 - */
 -enum libusb_log_cb_mode {
 -      /** Callback function handling all log messages. */
 -      LIBUSB_LOG_CB_GLOBAL = (1 << 0),
 -
 -      /** Callback function handling context related log messages. */
 -      LIBUSB_LOG_CB_CONTEXT = (1 << 1)
--};
 -
 -/** \ingroup libusb_lib
 - * Callback function for handling log messages.
 - * \param ctx the context which is related to the log message, or NULL if it
 - * is a global log message
 - * \param level the log level, see \ref libusb_log_level for a description
 - * \param str the log message
 - * \see libusb_set_log_cb()
 - */
 -typedef void (LIBUSB_CALL *libusb_log_cb)(libusb_context *ctx,
 -      enum libusb_log_level level, const char *str);
--
--int LIBUSB_CALL libusb_init(libusb_context **ctx);
--void LIBUSB_CALL libusb_exit(libusb_context *ctx);
--LIBUSB_DEPRECATED_FOR(libusb_set_option)
--void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level);
 -void LIBUSB_CALL libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb, int mode);
--const struct libusb_version * LIBUSB_CALL libusb_get_version(void);
--int LIBUSB_CALL libusb_has_capability(uint32_t capability);
--const char * LIBUSB_CALL libusb_error_name(int errcode);
--int LIBUSB_CALL libusb_setlocale(const char *locale);
- const char * LIBUSB_CALL libusb_strerror(enum libusb_error errcode);
 -const char * LIBUSB_CALL libusb_strerror(int errcode);
--
--ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx,
--      libusb_device ***list);
--void LIBUSB_CALL libusb_free_device_list(libusb_device **list,
--      int unref_devices);
--libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev);
--void LIBUSB_CALL libusb_unref_device(libusb_device *dev);
--
--int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev,
--      int *config);
--int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev,
--      struct libusb_device_descriptor *desc);
--int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev,
--      struct libusb_config_descriptor **config);
--int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev,
--      uint8_t config_index, struct libusb_config_descriptor **config);
--int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev,
--      uint8_t bConfigurationValue, struct libusb_config_descriptor **config);
--void LIBUSB_CALL libusb_free_config_descriptor(
--      struct libusb_config_descriptor *config);
--int LIBUSB_CALL libusb_get_ss_endpoint_companion_descriptor(
-       struct libusb_context *ctx,
 -      libusb_context *ctx,
--      const struct libusb_endpoint_descriptor *endpoint,
--      struct libusb_ss_endpoint_companion_descriptor **ep_comp);
--void LIBUSB_CALL libusb_free_ss_endpoint_companion_descriptor(
--      struct libusb_ss_endpoint_companion_descriptor *ep_comp);
--int LIBUSB_CALL libusb_get_bos_descriptor(libusb_device_handle *dev_handle,
--      struct libusb_bos_descriptor **bos);
--void LIBUSB_CALL libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos);
--int LIBUSB_CALL libusb_get_usb_2_0_extension_descriptor(
-       struct libusb_context *ctx,
 -      libusb_context *ctx,
--      struct libusb_bos_dev_capability_descriptor *dev_cap,
--      struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension);
--void LIBUSB_CALL libusb_free_usb_2_0_extension_descriptor(
--      struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension);
--int LIBUSB_CALL libusb_get_ss_usb_device_capability_descriptor(
-       struct libusb_context *ctx,
 -      libusb_context *ctx,
--      struct libusb_bos_dev_capability_descriptor *dev_cap,
--      struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap);
--void LIBUSB_CALL libusb_free_ss_usb_device_capability_descriptor(
--      struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap);
- int LIBUSB_CALL libusb_get_container_id_descriptor(struct libusb_context *ctx,
 -int LIBUSB_CALL libusb_get_container_id_descriptor(libusb_context *ctx,
--      struct libusb_bos_dev_capability_descriptor *dev_cap,
--      struct libusb_container_id_descriptor **container_id);
--void LIBUSB_CALL libusb_free_container_id_descriptor(
--      struct libusb_container_id_descriptor *container_id);
--uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev);
--uint8_t LIBUSB_CALL libusb_get_port_number(libusb_device *dev);
- int LIBUSB_CALL libusb_get_port_numbers(libusb_device *dev, uint8_t* port_numbers, int port_numbers_len);
 -int LIBUSB_CALL libusb_get_port_numbers(libusb_device *dev, uint8_t *port_numbers, int port_numbers_len);
--LIBUSB_DEPRECATED_FOR(libusb_get_port_numbers)
- int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_length);
 -int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t *path, uint8_t path_length);
--libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev);
--uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev);
--int LIBUSB_CALL libusb_get_device_speed(libusb_device *dev);
--int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev,
--      unsigned char endpoint);
--int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev,
--      unsigned char endpoint);
--
 -int LIBUSB_CALL libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev, libusb_device_handle **dev_handle);
--int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **dev_handle);
--void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle);
--libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle);
--
--int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev_handle,
--      int configuration);
--int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev_handle,
--      int interface_number);
--int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev_handle,
--      int interface_number);
--
--libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
--      libusb_context *ctx, uint16_t vendor_id, uint16_t product_id);
--
--int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
--      int interface_number, int alternate_setting);
--int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev_handle,
--      unsigned char endpoint);
--int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev_handle);
--
--int LIBUSB_CALL libusb_alloc_streams(libusb_device_handle *dev_handle,
--      uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
--int LIBUSB_CALL libusb_free_streams(libusb_device_handle *dev_handle,
--      unsigned char *endpoints, int num_endpoints);
--
--unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
--      size_t length);
--int LIBUSB_CALL libusb_dev_mem_free(libusb_device_handle *dev_handle,
--      unsigned char *buffer, size_t length);
--
--int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev_handle,
--      int interface_number);
--int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
--      int interface_number);
--int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
--      int interface_number);
--int LIBUSB_CALL libusb_set_auto_detach_kernel_driver(
--      libusb_device_handle *dev_handle, int enable);
--
--/* async I/O */
--
--/** \ingroup libusb_asyncio
-- * Get the data section of a control transfer. This convenience function is here
-- * to remind you that the data does not start until 8 bytes into the actual
-- * buffer, as the setup packet comes first.
-- *
-- * Calling this function only makes sense from a transfer callback function,
-- * or situations where you have already allocated a suitably sized buffer at
-- * transfer->buffer.
-- *
-- * \param transfer a transfer
-- * \returns pointer to the first byte of the data section
-- */
--static inline unsigned char *libusb_control_transfer_get_data(
--      struct libusb_transfer *transfer)
--{
--      return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
--}
--
--/** \ingroup libusb_asyncio
-- * Get the control setup packet of a control transfer. This convenience
-- * function is here to remind you that the control setup occupies the first
-- * 8 bytes of the transfer data buffer.
-- *
-- * Calling this function only makes sense from a transfer callback function,
-- * or situations where you have already allocated a suitably sized buffer at
-- * transfer->buffer.
-- *
-- * \param transfer a transfer
-- * \returns a casted pointer to the start of the transfer data buffer
-- */
--static inline struct libusb_control_setup *libusb_control_transfer_get_setup(
--      struct libusb_transfer *transfer)
--{
-       return (struct libusb_control_setup *)(void *) transfer->buffer;
 -      return (struct libusb_control_setup *)(void *)transfer->buffer;
--}
--
--/** \ingroup libusb_asyncio
-- * Helper function to populate the setup packet (first 8 bytes of the data
-- * buffer) for a control transfer. The wIndex, wValue and wLength values should
-- * be given in host-endian byte order.
-- *
-- * \param buffer buffer to output the setup packet into
-- * This pointer must be aligned to at least 2 bytes boundary.
-- * \param bmRequestType see the
-- * \ref libusb_control_setup::bmRequestType "bmRequestType" field of
-- * \ref libusb_control_setup
-- * \param bRequest see the
-- * \ref libusb_control_setup::bRequest "bRequest" field of
-- * \ref libusb_control_setup
-- * \param wValue see the
-- * \ref libusb_control_setup::wValue "wValue" field of
-- * \ref libusb_control_setup
-- * \param wIndex see the
-- * \ref libusb_control_setup::wIndex "wIndex" field of
-- * \ref libusb_control_setup
-- * \param wLength see the
-- * \ref libusb_control_setup::wLength "wLength" field of
-- * \ref libusb_control_setup
-- */
--static inline void libusb_fill_control_setup(unsigned char *buffer,
--      uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
--      uint16_t wLength)
--{
-       struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer;
 -      struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *)buffer;
--      setup->bmRequestType = bmRequestType;
--      setup->bRequest = bRequest;
--      setup->wValue = libusb_cpu_to_le16(wValue);
--      setup->wIndex = libusb_cpu_to_le16(wIndex);
--      setup->wLength = libusb_cpu_to_le16(wLength);
--}
--
--struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets);
--int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer);
--int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer);
--void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer);
--void LIBUSB_CALL libusb_transfer_set_stream_id(
--      struct libusb_transfer *transfer, uint32_t stream_id);
--uint32_t LIBUSB_CALL libusb_transfer_get_stream_id(
--      struct libusb_transfer *transfer);
--
--/** \ingroup libusb_asyncio
-- * Helper function to populate the required \ref libusb_transfer fields
-- * for a control transfer.
-- *
-- * If you pass a transfer buffer to this function, the first 8 bytes will
-- * be interpreted as a control setup packet, and the wLength field will be
-- * used to automatically populate the \ref libusb_transfer::length "length"
-- * field of the transfer. Therefore the recommended approach is:
-- * -# Allocate a suitably sized data buffer (including space for control setup)
-- * -# Call libusb_fill_control_setup()
-- * -# If this is a host-to-device transfer with a data stage, put the data
-- *    in place after the setup packet
-- * -# Call this function
-- * -# Call libusb_submit_transfer()
-- *
-- * It is also legal to pass a NULL buffer to this function, in which case this
-- * function will not attempt to populate the length field. Remember that you
-- * must then populate the buffer and length fields later.
-- *
-- * \param transfer the transfer to populate
-- * \param dev_handle handle of the device that will handle the transfer
-- * \param buffer data buffer. If provided, this function will interpret the
-- * first 8 bytes as a setup packet and infer the transfer length from that.
-- * This pointer must be aligned to at least 2 bytes boundary.
-- * \param callback callback function to be invoked on transfer completion
-- * \param user_data user data to pass to callback function
-- * \param timeout timeout for the transfer in milliseconds
-- */
--static inline void libusb_fill_control_transfer(
--      struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
--      unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data,
--      unsigned int timeout)
--{
-       struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer;
 -      struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *)buffer;
--      transfer->dev_handle = dev_handle;
--      transfer->endpoint = 0;
--      transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL;
--      transfer->timeout = timeout;
--      transfer->buffer = buffer;
--      if (setup)
--              transfer->length = (int) (LIBUSB_CONTROL_SETUP_SIZE
--                      + libusb_le16_to_cpu(setup->wLength));
--      transfer->user_data = user_data;
--      transfer->callback = callback;
--}
--
--/** \ingroup libusb_asyncio
-- * Helper function to populate the required \ref libusb_transfer fields
-- * for a bulk transfer.
-- *
-- * \param transfer the transfer to populate
-- * \param dev_handle handle of the device that will handle the transfer
-- * \param endpoint address of the endpoint where this transfer will be sent
-- * \param buffer data buffer
-- * \param length length of data buffer
-- * \param callback callback function to be invoked on transfer completion
-- * \param user_data user data to pass to callback function
-- * \param timeout timeout for the transfer in milliseconds
-- */
--static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer,
--      libusb_device_handle *dev_handle, unsigned char endpoint,
--      unsigned char *buffer, int length, libusb_transfer_cb_fn callback,
--      void *user_data, unsigned int timeout)
--{
--      transfer->dev_handle = dev_handle;
--      transfer->endpoint = endpoint;
--      transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
--      transfer->timeout = timeout;
--      transfer->buffer = buffer;
--      transfer->length = length;
--      transfer->user_data = user_data;
--      transfer->callback = callback;
--}
--
--/** \ingroup libusb_asyncio
-- * Helper function to populate the required \ref libusb_transfer fields
-- * for a bulk transfer using bulk streams.
-- *
-- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
-- *
-- * \param transfer the transfer to populate
-- * \param dev_handle handle of the device that will handle the transfer
-- * \param endpoint address of the endpoint where this transfer will be sent
-- * \param stream_id bulk stream id for this transfer
-- * \param buffer data buffer
-- * \param length length of data buffer
-- * \param callback callback function to be invoked on transfer completion
-- * \param user_data user data to pass to callback function
-- * \param timeout timeout for the transfer in milliseconds
-- */
--static inline void libusb_fill_bulk_stream_transfer(
--      struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
--      unsigned char endpoint, uint32_t stream_id,
--      unsigned char *buffer, int length, libusb_transfer_cb_fn callback,
--      void *user_data, unsigned int timeout)
--{
--      libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer,
--                                length, callback, user_data, timeout);
--      transfer->type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
--      libusb_transfer_set_stream_id(transfer, stream_id);
--}
--
--/** \ingroup libusb_asyncio
-- * Helper function to populate the required \ref libusb_transfer fields
-- * for an interrupt transfer.
-- *
-- * \param transfer the transfer to populate
-- * \param dev_handle handle of the device that will handle the transfer
-- * \param endpoint address of the endpoint where this transfer will be sent
-- * \param buffer data buffer
-- * \param length length of data buffer
-- * \param callback callback function to be invoked on transfer completion
-- * \param user_data user data to pass to callback function
-- * \param timeout timeout for the transfer in milliseconds
-- */
--static inline void libusb_fill_interrupt_transfer(
--      struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
--      unsigned char endpoint, unsigned char *buffer, int length,
--      libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
--{
--      transfer->dev_handle = dev_handle;
--      transfer->endpoint = endpoint;
--      transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
--      transfer->timeout = timeout;
--      transfer->buffer = buffer;
--      transfer->length = length;
--      transfer->user_data = user_data;
--      transfer->callback = callback;
--}
--
--/** \ingroup libusb_asyncio
-- * Helper function to populate the required \ref libusb_transfer fields
-- * for an isochronous transfer.
-- *
-- * \param transfer the transfer to populate
-- * \param dev_handle handle of the device that will handle the transfer
-- * \param endpoint address of the endpoint where this transfer will be sent
-- * \param buffer data buffer
-- * \param length length of data buffer
-- * \param num_iso_packets the number of isochronous packets
-- * \param callback callback function to be invoked on transfer completion
-- * \param user_data user data to pass to callback function
-- * \param timeout timeout for the transfer in milliseconds
-- */
--static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer,
--      libusb_device_handle *dev_handle, unsigned char endpoint,
--      unsigned char *buffer, int length, int num_iso_packets,
--      libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
--{
--      transfer->dev_handle = dev_handle;
--      transfer->endpoint = endpoint;
--      transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
--      transfer->timeout = timeout;
--      transfer->buffer = buffer;
--      transfer->length = length;
--      transfer->num_iso_packets = num_iso_packets;
--      transfer->user_data = user_data;
--      transfer->callback = callback;
--}
--
--/** \ingroup libusb_asyncio
-- * Convenience function to set the length of all packets in an isochronous
-- * transfer, based on the num_iso_packets field in the transfer structure.
-- *
-- * \param transfer a transfer
-- * \param length the length to set in each isochronous packet descriptor
-- * \see libusb_get_max_packet_size()
-- */
--static inline void libusb_set_iso_packet_lengths(
--      struct libusb_transfer *transfer, unsigned int length)
--{
--      int i;
 -
--      for (i = 0; i < transfer->num_iso_packets; i++)
--              transfer->iso_packet_desc[i].length = length;
--}
--
--/** \ingroup libusb_asyncio
-- * Convenience function to locate the position of an isochronous packet
-- * within the buffer of an isochronous transfer.
-- *
-- * This is a thorough function which loops through all preceding packets,
-- * accumulating their lengths to find the position of the specified packet.
-- * Typically you will assign equal lengths to each packet in the transfer,
-- * and hence the above method is sub-optimal. You may wish to use
-- * libusb_get_iso_packet_buffer_simple() instead.
-- *
-- * \param transfer a transfer
-- * \param packet the packet to return the address of
-- * \returns the base address of the packet buffer inside the transfer buffer,
-- * or NULL if the packet does not exist.
-- * \see libusb_get_iso_packet_buffer_simple()
-- */
--static inline unsigned char *libusb_get_iso_packet_buffer(
--      struct libusb_transfer *transfer, unsigned int packet)
--{
--      int i;
--      size_t offset = 0;
--      int _packet;
--
--      /* oops..slight bug in the API. packet is an unsigned int, but we use
--       * signed integers almost everywhere else. range-check and convert to
--       * signed to avoid compiler warnings. FIXME for libusb-2. */
--      if (packet > INT_MAX)
--              return NULL;
--      _packet = (int) packet;
--
--      if (_packet >= transfer->num_iso_packets)
--              return NULL;
--
--      for (i = 0; i < _packet; i++)
--              offset += transfer->iso_packet_desc[i].length;
--
--      return transfer->buffer + offset;
--}
--
--/** \ingroup libusb_asyncio
-- * Convenience function to locate the position of an isochronous packet
-- * within the buffer of an isochronous transfer, for transfers where each
-- * packet is of identical size.
-- *
-- * This function relies on the assumption that every packet within the transfer
-- * is of identical size to the first packet. Calculating the location of
-- * the packet buffer is then just a simple calculation:
-- * <tt>buffer + (packet_size * packet)</tt>
-- *
-- * Do not use this function on transfers other than those that have identical
-- * packet lengths for each packet.
-- *
-- * \param transfer a transfer
-- * \param packet the packet to return the address of
-- * \returns the base address of the packet buffer inside the transfer buffer,
-- * or NULL if the packet does not exist.
-- * \see libusb_get_iso_packet_buffer()
-- */
--static inline unsigned char *libusb_get_iso_packet_buffer_simple(
--      struct libusb_transfer *transfer, unsigned int packet)
--{
--      int _packet;
--
--      /* oops..slight bug in the API. packet is an unsigned int, but we use
--       * signed integers almost everywhere else. range-check and convert to
--       * signed to avoid compiler warnings. FIXME for libusb-2. */
--      if (packet > INT_MAX)
--              return NULL;
--      _packet = (int) packet;
--
--      if (_packet >= transfer->num_iso_packets)
--              return NULL;
--
--      return transfer->buffer + ((int) transfer->iso_packet_desc[0].length * _packet);
--}
--
--/* sync I/O */
--
--int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle,
--      uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
--      unsigned char *data, uint16_t wLength, unsigned int timeout);
--
--int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle,
--      unsigned char endpoint, unsigned char *data, int length,
--      int *actual_length, unsigned int timeout);
--
--int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle,
--      unsigned char endpoint, unsigned char *data, int length,
--      int *actual_length, unsigned int timeout);
--
--/** \ingroup libusb_desc
-- * Retrieve a descriptor from the default control pipe.
-- * This is a convenience function which formulates the appropriate control
-- * message to retrieve the descriptor.
-- *
-- * \param dev_handle a device handle
-- * \param desc_type the descriptor type, see \ref libusb_descriptor_type
-- * \param desc_index the index of the descriptor to retrieve
-- * \param data output buffer for descriptor
-- * \param length size of data buffer
-- * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
-- */
--static inline int libusb_get_descriptor(libusb_device_handle *dev_handle,
--      uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length)
--{
--      return libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
--              LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t) ((desc_type << 8) | desc_index),
--              0, data, (uint16_t) length, 1000);
--}
--
--/** \ingroup libusb_desc
-- * Retrieve a descriptor from a device.
-- * This is a convenience function which formulates the appropriate control
-- * message to retrieve the descriptor. The string returned is Unicode, as
-- * detailed in the USB specifications.
-- *
-- * \param dev_handle a device handle
-- * \param desc_index the index of the descriptor to retrieve
-- * \param langid the language ID for the string descriptor
-- * \param data output buffer for descriptor
-- * \param length size of data buffer
-- * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
-- * \see libusb_get_string_descriptor_ascii()
-- */
--static inline int libusb_get_string_descriptor(libusb_device_handle *dev_handle,
--      uint8_t desc_index, uint16_t langid, unsigned char *data, int length)
--{
--      return libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
--              LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t)((LIBUSB_DT_STRING << 8) | desc_index),
--              langid, data, (uint16_t) length, 1000);
--}
--
--int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle,
--      uint8_t desc_index, unsigned char *data, int length);
--
--/* polling and timeouts */
--
--int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx);
--void LIBUSB_CALL libusb_lock_events(libusb_context *ctx);
--void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx);
--int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx);
--int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx);
--void LIBUSB_CALL libusb_interrupt_event_handler(libusb_context *ctx);
--void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx);
--void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx);
--int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv);
--
--int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx,
--      struct timeval *tv);
--int LIBUSB_CALL libusb_handle_events_timeout_completed(libusb_context *ctx,
--      struct timeval *tv, int *completed);
--int LIBUSB_CALL libusb_handle_events(libusb_context *ctx);
--int LIBUSB_CALL libusb_handle_events_completed(libusb_context *ctx, int *completed);
--int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx,
--      struct timeval *tv);
--int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx);
--int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx,
--      struct timeval *tv);
--
--/** \ingroup libusb_poll
-- * File descriptor for polling
-- */
--struct libusb_pollfd {
--      /** Numeric file descriptor */
--      int fd;
--
--      /** Event flags to poll for from <poll.h>. POLLIN indicates that you
--       * should monitor this file descriptor for becoming ready to read from,
--       * and POLLOUT indicates that you should monitor this file descriptor for
--       * nonblocking write readiness. */
--      short events;
--};
--
--/** \ingroup libusb_poll
-- * Callback function, invoked when a new file descriptor should be added
-- * to the set of file descriptors monitored for events.
-- * \param fd the new file descriptor
-- * \param events events to monitor for, see \ref libusb_pollfd for a
-- * description
-- * \param user_data User data pointer specified in
-- * libusb_set_pollfd_notifiers() call
-- * \see libusb_set_pollfd_notifiers()
-- */
--typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events,
--      void *user_data);
--
--/** \ingroup libusb_poll
-- * Callback function, invoked when a file descriptor should be removed from
-- * the set of file descriptors being monitored for events. After returning
-- * from this callback, do not use that file descriptor again.
-- * \param fd the file descriptor to stop monitoring
-- * \param user_data User data pointer specified in
-- * libusb_set_pollfd_notifiers() call
-- * \see libusb_set_pollfd_notifiers()
-- */
--typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data);
--
--const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
--      libusb_context *ctx);
--void LIBUSB_CALL libusb_free_pollfds(const struct libusb_pollfd **pollfds);
--void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx,
--      libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
--      void *user_data);
--
--/** \ingroup libusb_hotplug
-- * Callback handle.
-- *
-- * Callbacks handles are generated by libusb_hotplug_register_callback()
-- * and can be used to deregister callbacks. Callback handles are unique
-- * per libusb_context and it is safe to call libusb_hotplug_deregister_callback()
-  * on an already deregisted callback.
 - * on an already deregistered callback.
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- *
-- * For more information, see \ref libusb_hotplug.
-- */
--typedef int libusb_hotplug_callback_handle;
--
--/** \ingroup libusb_hotplug
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- *
-  * Flags for hotplug events */
 - * Hotplug events */
--typedef enum {
-       /** Default value when not using any flags. */
-       LIBUSB_HOTPLUG_NO_FLAGS = 0,
 -      /** A device has been plugged in and is ready to use */
 -      LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED = (1 << 0),
--
-       /** Arm the callback and fire it for all matching currently attached devices. */
-       LIBUSB_HOTPLUG_ENUMERATE = 1<<0,
- } libusb_hotplug_flag;
 -      /** A device has left and is no longer available.
 -       * It is the user's responsibility to call libusb_close on any handle associated with a disconnected device.
 -       * It is safe to call libusb_get_device_descriptor on a device that has left */
 -      LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT = (1 << 1)
 -} libusb_hotplug_event;
--
--/** \ingroup libusb_hotplug
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- *
-  * Hotplug events */
 - * Hotplug flags */
--typedef enum {
-       /** A device has been plugged in and is ready to use */
-       LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01,
 -      /** Arm the callback and fire it for all matching currently attached devices. */
 -      LIBUSB_HOTPLUG_ENUMERATE = (1 << 0)
 -} libusb_hotplug_flag;
--
-       /** A device has left and is no longer available.
-        * It is the user's responsibility to call libusb_close on any handle associated with a disconnected device.
-        * It is safe to call libusb_get_device_descriptor on a device that has left */
-       LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT    = 0x02,
- } libusb_hotplug_event;
 -/** \ingroup libusb_hotplug
 - * Convenience macro when not using any flags */
 -#define LIBUSB_HOTPLUG_NO_FLAGS 0
--
--/** \ingroup libusb_hotplug
-- * Wildcard matching for hotplug events */
--#define LIBUSB_HOTPLUG_MATCH_ANY -1
--
--/** \ingroup libusb_hotplug
-- * Hotplug callback function type. When requesting hotplug event notifications,
-- * you pass a pointer to a callback function of this type.
-- *
-- * This callback may be called by an internal event thread and as such it is
-- * recommended the callback do minimal processing before returning.
-- *
-- * libusb will call this function later, when a matching event had happened on
-- * a matching device. See \ref libusb_hotplug for more information.
-- *
-- * It is safe to call either libusb_hotplug_register_callback() or
-- * libusb_hotplug_deregister_callback() from within a callback function.
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- *
-- * \param ctx            context of this notification
-- * \param device         libusb_device this event occurred on
-- * \param event          event that occurred
-- * \param user_data      user data provided when this callback was registered
-- * \returns bool whether this callback is finished processing events.
-- *                       returning 1 will cause this callback to be deregistered
-- */
--typedef int (LIBUSB_CALL *libusb_hotplug_callback_fn)(libusb_context *ctx,
-                                               libusb_device *device,
-                                               libusb_hotplug_event event,
-                                               void *user_data);
 -      libusb_device *device, libusb_hotplug_event event, void *user_data);
--
--/** \ingroup libusb_hotplug
-- * Register a hotplug callback function
-- *
-- * Register a callback with the libusb_context. The callback will fire
-- * when a matching event occurs on a matching device. The callback is
-- * armed until either it is deregistered with libusb_hotplug_deregister_callback()
-- * or the supplied callback returns 1 to indicate it is finished processing events.
-- *
-- * If the \ref LIBUSB_HOTPLUG_ENUMERATE is passed the callback will be
-- * called with a \ref LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED for all devices
-- * already plugged into the machine. Note that libusb modifies its internal
-- * device list from a separate thread, while calling hotplug callbacks from
-- * libusb_handle_events(), so it is possible for a device to already be present
-- * on, or removed from, its internal device list, while the hotplug callbacks
-- * still need to be dispatched. This means that when using \ref
-- * LIBUSB_HOTPLUG_ENUMERATE, your callback may be called twice for the arrival
-- * of the same device, once from libusb_hotplug_register_callback() and once
-- * from libusb_handle_events(); and/or your callback may be called for the
-- * removal of a device for which an arrived call was never made.
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- *
-- * \param[in] ctx context to register this callback with
-  * \param[in] events bitwise or of events that will trigger this callback. See \ref
-  *            libusb_hotplug_event
-  * \param[in] flags hotplug callback flags. See \ref libusb_hotplug_flag
 - * \param[in] events bitwise or of hotplug events that will trigger this callback.
 - *            See \ref libusb_hotplug_event
 - * \param[in] flags bitwise or of hotplug flags that affect registration.
 - *            See \ref libusb_hotplug_flag
-- * \param[in] vendor_id the vendor id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY
-- * \param[in] product_id the product id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY
-- * \param[in] dev_class the device class to match or \ref LIBUSB_HOTPLUG_MATCH_ANY
-- * \param[in] cb_fn the function to be invoked on a matching event/device
-- * \param[in] user_data user data to pass to the callback function
-- * \param[out] callback_handle pointer to store the handle of the allocated callback (can be NULL)
-- * \returns LIBUSB_SUCCESS on success LIBUSB_ERROR code on failure
-- */
--int LIBUSB_CALL libusb_hotplug_register_callback(libusb_context *ctx,
-                                               libusb_hotplug_event events,
-                                               libusb_hotplug_flag flags,
-                                               int vendor_id, int product_id,
-                                               int dev_class,
-                                               libusb_hotplug_callback_fn cb_fn,
-                                               void *user_data,
-                                               libusb_hotplug_callback_handle *callback_handle);
 -      int events, int flags,
 -      int vendor_id, int product_id, int dev_class,
 -      libusb_hotplug_callback_fn cb_fn, void *user_data,
 -      libusb_hotplug_callback_handle *callback_handle);
--
--/** \ingroup libusb_hotplug
-- * Deregisters a hotplug callback.
-- *
-- * Deregister a callback from a libusb_context. This function is safe to call from within
-- * a hotplug callback.
-- *
-- * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
-- *
-- * \param[in] ctx context this callback is registered with
-- * \param[in] callback_handle the handle of the callback to deregister
-- */
--void LIBUSB_CALL libusb_hotplug_deregister_callback(libusb_context *ctx,
-                                               libusb_hotplug_callback_handle callback_handle);
 -      libusb_hotplug_callback_handle callback_handle);
 -
 -/** \ingroup libusb_hotplug
 - * Gets the user_data associated with a hotplug callback.
 - *
 - * Since version v1.0.24 \ref LIBUSB_API_VERSION >= 0x01000108
 - *
 - * \param[in] ctx context this callback is registered with
 - * \param[in] callback_handle the handle of the callback to get the user_data of
 - */
 -void * LIBUSB_CALL libusb_hotplug_get_user_data(libusb_context *ctx,
 -      libusb_hotplug_callback_handle callback_handle);
--
--/** \ingroup libusb_lib
-- * Available option values for libusb_set_option().
-- */
--enum libusb_option {
--      /** Set the log message verbosity.
--       *
--       * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
--       * printed. If you choose to increase the message verbosity level, ensure
--       * that your application does not close the stderr file descriptor.
--       *
--       * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
--       * with its message logging and most of the time, will only log messages that
--       * explain error conditions and other oddities. This will help you debug
--       * your software.
--       *
--       * If the LIBUSB_DEBUG environment variable was set when libusb was
--       * initialized, this function does nothing: the message verbosity is fixed
--       * to the value in the environment variable.
--       *
--       * If libusb was compiled without any message logging, this function does
--       * nothing: you'll never get any messages.
--       *
--       * If libusb was compiled with verbose debug message logging, this function
--       * does nothing: you'll always get messages from all levels.
--       */
-       LIBUSB_OPTION_LOG_LEVEL,
 -      LIBUSB_OPTION_LOG_LEVEL = 0,
--
--      /** Use the UsbDk backend for a specific context, if available.
--       *
--       * This option should be set immediately after calling libusb_init(), otherwise
--       * unspecified behavior may occur.
--       *
--       * Only valid on Windows.
--       */
-       LIBUSB_OPTION_USE_USBDK,
 -      LIBUSB_OPTION_USE_USBDK = 1,
 -
 -      /** Set libusb has weak authority. With this option, libusb will skip
 -       * scan devices in libusb_init.
 -       *
 -       * This option should be set before calling libusb_init(), otherwise
 -       * libusb_init will failed. Normally libusb_wrap_sys_device need set
 -       * this option.
 -       *
 -       * Only valid on Linux-based operating system, such as Android.
 -       */
 -      LIBUSB_OPTION_WEAK_AUTHORITY = 2
--};
--
--int LIBUSB_CALL libusb_set_option(libusb_context *ctx, enum libusb_option option, ...);
--
- #ifdef __cplusplus
 -#if defined(__cplusplus)
--}
--#endif
--
--#endif
diff --cc mac/libusb/libusb.pro
index a5d543756c200b25648d3acc3f0b8cb1b9eaaf14,07c7d23dad6b77f61ec7a8ad9b76c72af575ee2c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,34 -1,34 +1,0 @@@
--# Were using qmake to build a library that has nothing to do with Qt.
--# Dummy out qt defaults.
--QT -= gui
--QT -= core
--
--CONFIG += staticlib
--TEMPLATE = lib
--
--TARGET = usb-1.0
--
--SOURCES = core.c \
--  descriptor.c \
--  hotplug.c \
--  io.c \
--  strerror.c \
--  sync.c \
--  os/darwin_usb.c \
-   os/poll_posix.c \
 -  os/events_posix.c \
--  os/threads_posix.c
--
--HEADERS = hotplug.h \
--  libusb.h \
--  libusbi.h \
--  version.h \
--  version_nano.h \
--  os/darwin_usb.h \
-   os/poll_posix.h \
 -  os/events_posix.h \
--  os/threads_posix.h
--
--# We use libusb-1.0.0's hardcoded config.h for Xcode
--# Note that we want don't want the path containing the Xcode config.h
--# to be found when building gpsbabel, i.e. it can't be next to libusb.h.
--INCLUDEPATH = Xcode
--
diff --cc mac/libusb/libusbi.h
index 31d6ce98d49cdb5c35c6d909e80032e2270514b2,491114be94a391a558f4aeec34a9a28f8c7a9fbd..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1165 -1,1372 +1,0 @@@
--/*
-- * Internal header for libusb
-- * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
-- * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
 - * Copyright © 2019 Nathan Hjelm <hjelmn@cs.umm.edu>
 - * Copyright © 2019-2020 Google LLC. All rights reserved.
 - * Copyright © 2020 Chris Dickens <christopher.a.dickens@gmail.com>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
--#ifndef LIBUSBI_H
--#define LIBUSBI_H
--
--#include <config.h>
- #include <stdlib.h>
--
- #include <stddef.h>
- #include <stdint.h>
- #include <time.h>
 -#include <assert.h>
 -#include <inttypes.h>
--#include <stdarg.h>
- #ifdef HAVE_POLL_H
- #include <poll.h>
- #endif
- #ifdef HAVE_MISSING_H
- #include <missing.h>
 -#include <stddef.h>
 -#include <stdlib.h>
 -#ifdef HAVE_SYS_TIME_H
 -#include <sys/time.h>
--#endif
--
--#include "libusb.h"
- #include "version.h"
--
- /* Attribute to ensure that a structure member is aligned to a natural
-  * pointer alignment. Used for os_priv member. */
- #if defined(_MSC_VER)
- #if defined(_WIN64)
- #define PTR_ALIGNED __declspec(align(8))
 -/* Not all C standard library headers define static_assert in assert.h
 - * Additionally, Visual Studio treats static_assert as a keyword.
 - */
 -#if !defined(__cplusplus) && !defined(static_assert) && !defined(_MSC_VER)
 -#define static_assert(cond, msg) _Static_assert(cond, msg)
 -#endif
 -
 -#ifdef NDEBUG
 -#define ASSERT_EQ(expression, value)  (void)expression
 -#define ASSERT_NE(expression, value)  (void)expression
--#else
- #define PTR_ALIGNED __declspec(align(4))
 -#define ASSERT_EQ(expression, value)  assert(expression == value)
 -#define ASSERT_NE(expression, value)  assert(expression != value)
--#endif
- #elif defined(__GNUC__)
- #define PTR_ALIGNED __attribute__((aligned(sizeof(void *))))
 -
 -#define container_of(ptr, type, member) \
 -      ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
 -
 -#ifndef ARRAYSIZE
 -#define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
 -#endif
 -
 -#ifndef CLAMP
 -#define CLAMP(val, min, max) \
 -      ((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))
 -#endif
 -
 -#ifndef MIN
 -#define MIN(a, b)     ((a) < (b) ? (a) : (b))
 -#endif
 -
 -#ifndef MAX
 -#define MAX(a, b)     ((a) > (b) ? (a) : (b))
 -#endif
 -
 -/* The following is used to silence warnings for unused variables */
 -#if defined(UNREFERENCED_PARAMETER)
 -#define UNUSED(var)   UNREFERENCED_PARAMETER(var)
--#else
- #define PTR_ALIGNED
 -#define UNUSED(var)   do { (void)(var); } while(0)
 -#endif
 -
 -/* Macro to align a value up to the next multiple of the size of a pointer */
 -#define PTR_ALIGN(v) \
 -      (((v) + (sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
 -
 -/* Internal abstractions for event handling and thread synchronization */
 -#if defined(PLATFORM_POSIX)
 -#include "os/events_posix.h"
 -#include "os/threads_posix.h"
 -#elif defined(PLATFORM_WINDOWS)
 -#include "os/events_windows.h"
 -#include "os/threads_windows.h"
--#endif
--
--/* Inside the libusb code, mark all public functions as follows:
-- *   return_type API_EXPORTED function_name(params) { ... }
-- * But if the function returns a pointer, mark it as follows:
-- *   DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
-- * In the libusb public header, mark all declarations as:
-- *   return_type LIBUSB_CALL function_name(params);
-- */
--#define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
--
--#ifdef __cplusplus
--extern "C" {
--#endif
- #define DEVICE_DESC_LENGTH    18
--
--#define USB_MAXENDPOINTS      32
--#define USB_MAXINTERFACES     32
--#define USB_MAXCONFIG         8
--
--/* Backend specific capabilities */
--#define USBI_CAP_HAS_HID_ACCESS                       0x00010000
--#define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER        0x00020000
--
--/* Maximum number of bytes in a log line */
--#define USBI_MAX_LOG_LEN      1024
--/* Terminator for log lines */
--#define USBI_LOG_LINE_END     "\n"
- /* The following is used to silence warnings for unused variables */
- #define UNUSED(var)           do { (void)(var); } while(0)
- #if !defined(ARRAYSIZE)
- #define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
- #endif
--
--struct list_head {
--      struct list_head *prev, *next;
--};
--
--/* Get an entry from the list
-- *  ptr - the address of this list_head element in "type"
-- *  type - the data type that contains "member"
-- *  member - the list_head element in "type"
-- */
--#define list_entry(ptr, type, member) \
-       ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
 -      container_of(ptr, type, member)
--
--#define list_first_entry(ptr, type, member) \
--      list_entry((ptr)->next, type, member)
 -
 -#define list_next_entry(ptr, type, member) \
 -      list_entry((ptr)->member.next, type, member)
--
--/* Get each entry from a list
-- *  pos - A structure pointer has a "member" element
-- *  head - list head
-- *  member - the list_head element in "pos"
-- *  type - the type of the first parameter
-- */
--#define list_for_each_entry(pos, head, member, type)                  \
-       for (pos = list_entry((head)->next, type, member);              \
 -      for (pos = list_first_entry(head, type, member);                \
--               &pos->member != (head);                                \
-                pos = list_entry(pos->member.next, type, member))
 -               pos = list_next_entry(pos, type, member))
--
--#define list_for_each_entry_safe(pos, n, head, member, type)          \
-       for (pos = list_entry((head)->next, type, member),              \
-                n = list_entry(pos->member.next, type, member);        \
 -      for (pos = list_first_entry(head, type, member),                \
 -               n = list_next_entry(pos, type, member);                \
--               &pos->member != (head);                                \
-                pos = n, n = list_entry(n->member.next, type, member))
 -               pos = n, n = list_next_entry(n, type, member))
 -
 -/* Helper macros to iterate over a list. The structure pointed
 - * to by "pos" must have a list_head member named "list".
 - */
 -#define for_each_helper(pos, head, type) \
 -      list_for_each_entry(pos, head, list, type)
 -
 -#define for_each_safe_helper(pos, n, head, type) \
 -      list_for_each_entry_safe(pos, n, head, list, type)
--
--#define list_empty(entry) ((entry)->next == (entry))
--
--static inline void list_init(struct list_head *entry)
--{
--      entry->prev = entry->next = entry;
--}
--
--static inline void list_add(struct list_head *entry, struct list_head *head)
--{
--      entry->next = head->next;
--      entry->prev = head;
--
--      head->next->prev = entry;
--      head->next = entry;
--}
--
--static inline void list_add_tail(struct list_head *entry,
--      struct list_head *head)
--{
--      entry->next = head;
--      entry->prev = head->prev;
--
--      head->prev->next = entry;
--      head->prev = entry;
--}
--
--static inline void list_del(struct list_head *entry)
--{
--      entry->next->prev = entry->prev;
--      entry->prev->next = entry->next;
--      entry->next = entry->prev = NULL;
--}
--
--static inline void list_cut(struct list_head *list, struct list_head *head)
--{
-       if (list_empty(head))
 -      if (list_empty(head)) {
 -              list_init(list);
--              return;
 -      }
--
--      list->next = head->next;
--      list->next->prev = list;
--      list->prev = head->prev;
--      list->prev->next = list;
--
--      list_init(head);
 -}
 -
 -static inline void list_splice_front(struct list_head *list, struct list_head *head)
 -{
 -      list->next->prev = head;
 -      list->prev->next = head->next;
 -      head->next->prev = list->prev;
 -      head->next = list->next;
--}
--
--static inline void *usbi_reallocf(void *ptr, size_t size)
--{
--      void *ret = realloc(ptr, size);
 -
--      if (!ret)
--              free(ptr);
--      return ret;
--}
- #define container_of(ptr, type, member) ({                    \
-       const typeof( ((type *)0)->member ) *mptr = (ptr);      \
-       (type *)( (char *)mptr - offsetof(type,member) );})
--
- #ifndef CLAMP
- #define CLAMP(val, min, max) ((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))
- #endif
- #ifndef MIN
- #define MIN(a, b)     ((a) < (b) ? (a) : (b))
 -#if !defined(USEC_PER_SEC)
 -#define USEC_PER_SEC  1000000L
--#endif
- #ifndef MAX
- #define MAX(a, b)     ((a) > (b) ? (a) : (b))
 -
 -#if !defined(NSEC_PER_SEC)
 -#define NSEC_PER_SEC  1000000000L
--#endif
--
- #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
 -#define TIMEVAL_IS_VALID(tv)                                          \
 -      ((tv)->tv_sec >= 0 &&                                           \
 -       (tv)->tv_usec >= 0 && (tv)->tv_usec < USEC_PER_SEC)
--
- #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
 -#define TIMESPEC_IS_SET(ts)   ((ts)->tv_sec || (ts)->tv_nsec)
 -#define TIMESPEC_CLEAR(ts)    (ts)->tv_sec = (ts)->tv_nsec = 0
 -#define TIMESPEC_CMP(a, b, CMP)                                               \
 -      (((a)->tv_sec == (b)->tv_sec)                                   \
 -       ? ((a)->tv_nsec CMP (b)->tv_nsec)                              \
 -       : ((a)->tv_sec CMP (b)->tv_sec))
 -#define TIMESPEC_SUB(a, b, result)                                    \
 -      do {                                                            \
 -              (result)->tv_sec = (a)->tv_sec - (b)->tv_sec;           \
 -              (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec;        \
 -              if ((result)->tv_nsec < 0L) {                           \
 -                      --(result)->tv_sec;                             \
 -                      (result)->tv_nsec += NSEC_PER_SEC;              \
 -              }                                                       \
 -      } while (0)
 -
 -#if defined(PLATFORM_WINDOWS)
--#define TIMEVAL_TV_SEC_TYPE   long
--#else
--#define TIMEVAL_TV_SEC_TYPE   time_t
--#endif
--
--/* Some platforms don't have this define */
--#ifndef TIMESPEC_TO_TIMEVAL
--#define TIMESPEC_TO_TIMEVAL(tv, ts)                                   \
--      do {                                                            \
--              (tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec;      \
-               (tv)->tv_usec = (ts)->tv_nsec / 1000;                   \
 -              (tv)->tv_usec = (ts)->tv_nsec / 1000L;                  \
--      } while (0)
--#endif
--
--#ifdef ENABLE_LOGGING
--
--#if defined(_MSC_VER) && (_MSC_VER < 1900)
 -#include <stdio.h>
--#define snprintf usbi_snprintf
--#define vsnprintf usbi_vsnprintf
--int usbi_snprintf(char *dst, size_t size, const char *format, ...);
- int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list ap);
 -int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list args);
--#define LIBUSB_PRINTF_WIN32
--#endif /* defined(_MSC_VER) && (_MSC_VER < 1900) */
--
--void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
-       const char *function, const char *format, ...);
- void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
-       const char *function, const char *format, va_list args);
- #if !defined(_MSC_VER) || (_MSC_VER >= 1400)
- #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
- #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
- #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
- #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
- #define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
- #else /* !defined(_MSC_VER) || (_MSC_VER >= 1400) */
- #define LOG_BODY(ctxt, level)                         \
- {                                                     \
-       va_list args;                                   \
-       va_start(args, format);                         \
-       usbi_log_v(ctxt, level, "", format, args);      \
-       va_end(args);                                   \
- }
 -      const char *function, const char *format, ...) PRINTF_FORMAT(4, 5);
--
- static inline void usbi_err(struct libusb_context *ctx, const char *format, ...)
-       LOG_BODY(ctx, LIBUSB_LOG_LEVEL_ERROR)
- static inline void usbi_warn(struct libusb_context *ctx, const char *format, ...)
-       LOG_BODY(ctx, LIBUSB_LOG_LEVEL_WARNING)
- static inline void usbi_info(struct libusb_context *ctx, const char *format, ...)
-       LOG_BODY(ctx, LIBUSB_LOG_LEVEL_INFO)
- static inline void usbi_dbg(const char *format, ...)
-       LOG_BODY(NULL, LIBUSB_LOG_LEVEL_DEBUG)
 -#define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __func__, __VA_ARGS__)
--
- #endif /* !defined(_MSC_VER) || (_MSC_VER >= 1400) */
 -#define usbi_err(ctx, ...)    _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
 -#define usbi_warn(ctx, ...)   _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
 -#define usbi_info(ctx, ...)   _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
 -#define usbi_dbg(...)         _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
--
--#else /* ENABLE_LOGGING */
--
- #define usbi_err(ctx, ...) do { (void)ctx; } while (0)
- #define usbi_warn(ctx, ...) do { (void)ctx; } while (0)
- #define usbi_info(ctx, ...) do { (void)ctx; } while (0)
- #define usbi_dbg(...) do {} while (0)
 -#define usbi_err(ctx, ...)    UNUSED(ctx)
 -#define usbi_warn(ctx, ...)   UNUSED(ctx)
 -#define usbi_info(ctx, ...)   UNUSED(ctx)
 -#define usbi_dbg(...)         do {} while (0)
--
--#endif /* ENABLE_LOGGING */
- #define USBI_GET_CONTEXT(ctx)                         \
-       do {                                            \
-               if (!(ctx))                             \
-                       (ctx) = usbi_default_context;   \
-       } while(0)
--
--#define DEVICE_CTX(dev)               ((dev)->ctx)
--#define HANDLE_CTX(handle)    (DEVICE_CTX((handle)->dev))
--#define TRANSFER_CTX(transfer)        (HANDLE_CTX((transfer)->dev_handle))
- #define ITRANSFER_CTX(transfer) \
-       (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
 -#define ITRANSFER_CTX(itransfer) \
 -      (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)))
--
--#define IS_EPIN(ep)           (0 != ((ep) & LIBUSB_ENDPOINT_IN))
--#define IS_EPOUT(ep)          (!IS_EPIN(ep))
--#define IS_XFERIN(xfer)               (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
--#define IS_XFEROUT(xfer)      (!IS_XFERIN(xfer))
- /* Internal abstraction for thread synchronization */
- #if defined(THREADS_POSIX)
- #include "os/threads_posix.h"
- #elif defined(OS_WINDOWS) || defined(OS_WINCE)
- #include "os/threads_windows.h"
- #endif
- extern struct libusb_context *usbi_default_context;
- /* Forward declaration for use in context (fully defined inside poll abstraction) */
- struct pollfd;
--
--struct libusb_context {
--#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
--      enum libusb_log_level debug;
--      int debug_fixed;
 -      libusb_log_cb log_handler;
--#endif
--
-       /* internal event pipe, used for signalling occurrence of an internal event. */
-       int event_pipe[2];
 -      /* used for signalling occurrence of an internal event. */
 -      usbi_event_t event;
 -
 -#ifdef HAVE_OS_TIMER
 -      /* used for timeout handling, if supported by OS.
 -       * this timer is maintained to trigger on the next pending timeout */
 -      usbi_timer_t timer;
 -#endif
--
--      struct list_head usb_devs;
--      usbi_mutex_t usb_devs_lock;
--
--      /* A list of open handles. Backends are free to traverse this if required.
--       */
--      struct list_head open_devs;
--      usbi_mutex_t open_devs_lock;
--
--      /* A list of registered hotplug callbacks */
--      struct list_head hotplug_cbs;
--      libusb_hotplug_callback_handle next_hotplug_cb_handle;
--      usbi_mutex_t hotplug_cbs_lock;
--
--      /* this is a list of in-flight transfer handles, sorted by timeout
--       * expiration. URBs to timeout the soonest are placed at the beginning of
--       * the list, URBs that will time out later are placed after, and urbs with
--       * infinite timeout are always placed at the very end. */
--      struct list_head flying_transfers;
--      /* Note paths taking both this and usbi_transfer->lock must always
--       * take this lock first */
--      usbi_mutex_t flying_transfers_lock;
--
 -#if !defined(PLATFORM_WINDOWS)
--      /* user callbacks for pollfd changes */
--      libusb_pollfd_added_cb fd_added_cb;
--      libusb_pollfd_removed_cb fd_removed_cb;
--      void *fd_cb_user_data;
 -#endif
--
--      /* ensures that only one thread is handling events at any one time */
--      usbi_mutex_t events_lock;
--
--      /* used to see if there is an active thread doing event handling */
--      int event_handler_active;
--
--      /* A thread-local storage key to track which thread is performing event
--       * handling */
--      usbi_tls_key_t event_handling_key;
--
--      /* used to wait for event completion in threads other than the one that is
--       * event handling */
--      usbi_mutex_t event_waiters_lock;
--      usbi_cond_t event_waiters_cond;
--
--      /* A lock to protect internal context event data. */
--      usbi_mutex_t event_data_lock;
--
--      /* A bitmask of flags that are set to indicate specific events that need to
--       * be handled. Protected by event_data_lock. */
--      unsigned int event_flags;
--
--      /* A counter that is set when we want to interrupt and prevent event handling,
--       * in order to safely close a device. Protected by event_data_lock. */
--      unsigned int device_close;
--
-       /* list and count of poll fds and an array of poll fd structures that is
-        * (re)allocated as necessary prior to polling. Protected by event_data_lock. */
-       struct list_head ipollfds;
-       struct pollfd *pollfds;
-       POLL_NFDS_TYPE pollfds_cnt;
 -      /* A list of currently active event sources. Protected by event_data_lock. */
 -      struct list_head event_sources;
 -
 -      /* A list of event sources that have been removed since the last time
 -       * event sources were waited on. Protected by event_data_lock. */
 -      struct list_head removed_event_sources;
 -
 -      /* A pointer and count to platform-specific data used for monitoring event
 -       * sources. Only accessed during event handling. */
 -      void *event_data;
 -      unsigned int event_data_cnt;
--
--      /* A list of pending hotplug messages. Protected by event_data_lock. */
--      struct list_head hotplug_msgs;
--
--      /* A list of pending completed transfers. Protected by event_data_lock. */
--      struct list_head completed_transfers;
- #ifdef USBI_TIMERFD_AVAILABLE
-       /* used for timeout handling, if supported by OS.
-        * this timerfd is maintained to trigger on the next pending timeout */
-       int timerfd;
- #endif
--
--      struct list_head list;
-       PTR_ALIGNED unsigned char os_priv[ZERO_SIZED_ARRAY];
--};
 -
 -extern struct libusb_context *usbi_default_context;
 -
 -extern struct list_head active_contexts_list;
 -extern usbi_mutex_static_t active_contexts_lock;
 -
 -static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
 -{
 -      return ctx ? ctx : usbi_default_context;
 -}
--
--enum usbi_event_flags {
-       /* The list of pollfds has been modified */
-       USBI_EVENT_POLLFDS_MODIFIED = 1 << 0,
 -      /* The list of event sources has been modified */
 -      USBI_EVENT_EVENT_SOURCES_MODIFIED = 1U << 0,
--
--      /* The user has interrupted the event handler */
-       USBI_EVENT_USER_INTERRUPT = 1 << 1,
 -      USBI_EVENT_USER_INTERRUPT = 1U << 1,
--
--      /* A hotplug callback deregistration is pending */
-       USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1 << 2,
- };
 -      USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1U << 2,
--
- /* Macros for managing event handling state */
- #define usbi_handling_events(ctx) \
-       (usbi_tls_key_get((ctx)->event_handling_key) != NULL)
 -      /* One or more hotplug messages are pending */
 -      USBI_EVENT_HOTPLUG_MSG_PENDING = 1U << 3,
--
- #define usbi_start_event_handling(ctx) \
-       usbi_tls_key_set((ctx)->event_handling_key, ctx)
 -      /* One or more completed transfers are pending */
 -      USBI_EVENT_TRANSFER_COMPLETED = 1U << 4,
--
- #define usbi_end_event_handling(ctx) \
-       usbi_tls_key_set((ctx)->event_handling_key, NULL)
 -      /* A device is in the process of being closed */
 -      USBI_EVENT_DEVICE_CLOSE = 1U << 5,
 -};
--
- /* Update the following macro if new event sources are added */
- #define usbi_pending_events(ctx) \
-       ((ctx)->event_flags || (ctx)->device_close \
-        || !list_empty(&(ctx)->hotplug_msgs) || !list_empty(&(ctx)->completed_transfers))
 -/* Macros for managing event handling state */
 -static inline int usbi_handling_events(struct libusb_context *ctx)
 -{
 -      return usbi_tls_key_get(ctx->event_handling_key) != NULL;
 -}
--
- #ifdef USBI_TIMERFD_AVAILABLE
- #define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
- #else
- #define usbi_using_timerfd(ctx) (0)
- #endif
 -static inline void usbi_start_event_handling(struct libusb_context *ctx)
 -{
 -      usbi_tls_key_set(ctx->event_handling_key, ctx);
 -}
 -
 -static inline void usbi_end_event_handling(struct libusb_context *ctx)
 -{
 -      usbi_tls_key_set(ctx->event_handling_key, NULL);
 -}
--
--struct libusb_device {
--      /* lock protects refcnt, everything else is finalized at initialization
--       * time */
--      usbi_mutex_t lock;
--      int refcnt;
--
--      struct libusb_context *ctx;
 -      struct libusb_device *parent_dev;
--
--      uint8_t bus_number;
--      uint8_t port_number;
-       struct libusb_device* parent_dev;
--      uint8_t device_address;
-       uint8_t num_configurations;
--      enum libusb_speed speed;
--
--      struct list_head list;
--      unsigned long session_data;
--
--      struct libusb_device_descriptor device_descriptor;
--      int attached;
-       PTR_ALIGNED unsigned char os_priv[ZERO_SIZED_ARRAY];
--};
--
--struct libusb_device_handle {
--      /* lock protects claimed_interfaces */
--      usbi_mutex_t lock;
--      unsigned long claimed_interfaces;
--
--      struct list_head list;
--      struct libusb_device *dev;
--      int auto_detach_kernel_driver;
-       PTR_ALIGNED unsigned char os_priv[ZERO_SIZED_ARRAY];
--};
--
- enum {
-       USBI_CLOCK_MONOTONIC,
-       USBI_CLOCK_REALTIME
- };
 -/* Function called by backend during device initialization to convert
 - * multi-byte fields in the device descriptor to host-endian format.
 - */
 -static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
 -{
 -      desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
 -      desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
 -      desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
 -      desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
 -}
 -
 -#ifdef HAVE_CLOCK_GETTIME
 -static inline void usbi_get_monotonic_time(struct timespec *tp)
 -{
 -      ASSERT_EQ(clock_gettime(CLOCK_MONOTONIC, tp), 0);
 -}
 -static inline void usbi_get_real_time(struct timespec *tp)
 -{
 -      ASSERT_EQ(clock_gettime(CLOCK_REALTIME, tp), 0);
 -}
 -#else
 -/* If the platform doesn't provide the clock_gettime() function, the backend
 - * must provide its own clock implementations.  Two clock functions are
 - * required:
 - *
 - *   usbi_get_monotonic_time(): returns the time since an unspecified starting
 - *                              point (usually boot) that is monotonically
 - *                              increasing.
 - *   usbi_get_real_time(): returns the time since system epoch.
 - */
 -void usbi_get_monotonic_time(struct timespec *tp);
 -void usbi_get_real_time(struct timespec *tp);
 -#endif
--
--/* in-memory transfer layout:
-- *
-  * 1. struct usbi_transfer
-  * 2. struct libusb_transfer (which includes iso packets) [variable size]
-  * 3. os private data [variable size]
 - * 1. os private data
 - * 2. struct usbi_transfer
 - * 3. struct libusb_transfer (which includes iso packets) [variable size]
-- *
-- * from a libusb_transfer, you can get the usbi_transfer by rewinding the
-- * appropriate number of bytes.
-  * the usbi_transfer includes the number of allocated packets, so you can
-  * determine the size of the transfer and hence the start and length of the
-  * OS-private data.
-- */
--
--struct usbi_transfer {
--      int num_iso_packets;
--      struct list_head list;
--      struct list_head completed_list;
-       struct timeval timeout;
 -      struct timespec timeout;
--      int transferred;
--      uint32_t stream_id;
-       uint8_t state_flags;   /* Protected by usbi_transfer->lock */
-       uint8_t timeout_flags; /* Protected by the flying_stransfers_lock */
 -      uint32_t state_flags;   /* Protected by usbi_transfer->lock */
 -      uint32_t timeout_flags; /* Protected by the flying_stransfers_lock */
--
--      /* this lock is held during libusb_submit_transfer() and
--       * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
--       * cancellation, submission-during-cancellation, etc). the OS backend
--       * should also take this lock in the handle_events path, to prevent the user
--       * cancelling the transfer from another thread while you are processing
--       * its completion (presumably there would be races within your OS backend
--       * if this were possible).
--       * Note paths taking both this and the flying_transfers_lock must
--       * always take the flying_transfers_lock first */
--      usbi_mutex_t lock;
 -
 -      void *priv;
--};
--
--enum usbi_transfer_state_flags {
--      /* Transfer successfully submitted by backend */
-       USBI_TRANSFER_IN_FLIGHT = 1 << 0,
 -      USBI_TRANSFER_IN_FLIGHT = 1U << 0,
--
--      /* Cancellation was requested via libusb_cancel_transfer() */
-       USBI_TRANSFER_CANCELLING = 1 << 1,
 -      USBI_TRANSFER_CANCELLING = 1U << 1,
--
--      /* Operation on the transfer failed because the device disappeared */
-       USBI_TRANSFER_DEVICE_DISAPPEARED = 1 << 2,
 -      USBI_TRANSFER_DEVICE_DISAPPEARED = 1U << 2,
--};
--
--enum usbi_transfer_timeout_flags {
--      /* Set by backend submit_transfer() if the OS handles timeout */
-       USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1 << 0,
 -      USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1U << 0,
--
--      /* The transfer timeout has been handled */
-       USBI_TRANSFER_TIMEOUT_HANDLED = 1 << 1,
 -      USBI_TRANSFER_TIMEOUT_HANDLED = 1U << 1,
--
--      /* The transfer timeout was successfully processed */
-       USBI_TRANSFER_TIMED_OUT = 1 << 2,
 -      USBI_TRANSFER_TIMED_OUT = 1U << 2,
--};
- #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)                    \
-       ((struct libusb_transfer *)(((unsigned char *)(transfer))       \
-               + sizeof(struct usbi_transfer)))
- #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)                    \
-       ((struct usbi_transfer *)(((unsigned char *)(transfer))         \
-               - sizeof(struct usbi_transfer)))
--
- static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
- {
-       return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
-               + sizeof(struct libusb_transfer)
-               + (transfer->num_iso_packets
-                       * sizeof(struct libusb_iso_packet_descriptor));
- }
 -#define USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)   \
 -      ((struct libusb_transfer *)                     \
 -       ((unsigned char *)(itransfer)                  \
 -        + PTR_ALIGN(sizeof(struct usbi_transfer))))
 -#define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)    \
 -      ((struct usbi_transfer *)                       \
 -       ((unsigned char *)(transfer)                   \
 -        - PTR_ALIGN(sizeof(struct usbi_transfer))))
--
- /* bus structures */
 -#ifdef _MSC_VER
 -#pragma pack(push, 1)
 -#endif
--
--/* All standard descriptors have these 2 fields in common */
- struct usb_descriptor_header {
-       uint8_t bLength;
-       uint8_t bDescriptorType;
 -struct usbi_descriptor_header {
 -      uint8_t  bLength;
 -      uint8_t  bDescriptorType;
 -} LIBUSB_PACKED;
 -
 -struct usbi_device_descriptor {
 -      uint8_t  bLength;
 -      uint8_t  bDescriptorType;
 -      uint16_t bcdUSB;
 -      uint8_t  bDeviceClass;
 -      uint8_t  bDeviceSubClass;
 -      uint8_t  bDeviceProtocol;
 -      uint8_t  bMaxPacketSize0;
 -      uint16_t idVendor;
 -      uint16_t idProduct;
 -      uint16_t bcdDevice;
 -      uint8_t  iManufacturer;
 -      uint8_t  iProduct;
 -      uint8_t  iSerialNumber;
 -      uint8_t  bNumConfigurations;
 -} LIBUSB_PACKED;
 -
 -struct usbi_configuration_descriptor {
 -      uint8_t  bLength;
 -      uint8_t  bDescriptorType;
 -      uint16_t wTotalLength;
 -      uint8_t  bNumInterfaces;
 -      uint8_t  bConfigurationValue;
 -      uint8_t  iConfiguration;
 -      uint8_t  bmAttributes;
 -      uint8_t  bMaxPower;
 -} LIBUSB_PACKED;
 -
 -struct usbi_interface_descriptor {
 -      uint8_t  bLength;
 -      uint8_t  bDescriptorType;
 -      uint8_t  bInterfaceNumber;
 -      uint8_t  bAlternateSetting;
 -      uint8_t  bNumEndpoints;
 -      uint8_t  bInterfaceClass;
 -      uint8_t  bInterfaceSubClass;
 -      uint8_t  bInterfaceProtocol;
 -      uint8_t  iInterface;
 -} LIBUSB_PACKED;
 -
 -struct usbi_string_descriptor {
 -      uint8_t  bLength;
 -      uint8_t  bDescriptorType;
 -      uint16_t wData[ZERO_SIZED_ARRAY];
 -} LIBUSB_PACKED;
 -
 -struct usbi_bos_descriptor {
 -      uint8_t  bLength;
 -      uint8_t  bDescriptorType;
 -      uint16_t wTotalLength;
 -      uint8_t  bNumDeviceCaps;
 -} LIBUSB_PACKED;
 -
 -#ifdef _MSC_VER
 -#pragma pack(pop)
 -#endif
 -
 -union usbi_config_desc_buf {
 -        struct usbi_configuration_descriptor desc;
 -        uint8_t buf[LIBUSB_DT_CONFIG_SIZE];
 -        uint16_t align;         /* Force 2-byte alignment */
 -};
 -
 -union usbi_string_desc_buf {
 -        struct usbi_string_descriptor desc;
 -        uint8_t buf[255];       /* Some devices choke on size > 255 */
 -        uint16_t align;         /* Force 2-byte alignment */
 -};
 -
 -union usbi_bos_desc_buf {
 -        struct usbi_bos_descriptor desc;
 -        uint8_t buf[LIBUSB_DT_BOS_SIZE];
 -        uint16_t align;         /* Force 2-byte alignment */
--};
--
--/* shared data and functions */
--
--int usbi_io_init(struct libusb_context *ctx);
--void usbi_io_exit(struct libusb_context *ctx);
--
--struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
--      unsigned long session_id);
--struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
--      unsigned long session_id);
--int usbi_sanitize_device(struct libusb_device *dev);
--void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
--
--int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
--      enum libusb_transfer_status status);
- int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
- void usbi_signal_transfer_completion(struct usbi_transfer *transfer);
 -int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer);
 -void usbi_signal_transfer_completion(struct usbi_transfer *itransfer);
--
- int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
-       void *dest, int host_endian);
- int usbi_device_cache_descriptor(libusb_device *dev);
- int usbi_get_config_index_by_value(struct libusb_device *dev,
-       uint8_t bConfigurationValue, int *idx);
 -void usbi_connect_device(struct libusb_device *dev);
 -void usbi_disconnect_device(struct libusb_device *dev);
--
- void usbi_connect_device (struct libusb_device *dev);
- void usbi_disconnect_device (struct libusb_device *dev);
 -struct usbi_event_source {
 -      struct usbi_event_source_data {
 -              usbi_os_handle_t os_handle;
 -              short poll_events;
 -      } data;
 -      struct list_head list;
 -};
--
- int usbi_signal_event(struct libusb_context *ctx);
- int usbi_clear_event(struct libusb_context *ctx);
 -int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle,
 -      short poll_events);
 -void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle);
--
- /* Internal abstraction for poll (needs struct usbi_transfer on Windows) */
- #if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD) || defined(OS_NETBSD) ||\
-       defined(OS_HAIKU) || defined(OS_SUNOS)
- #include <unistd.h>
- #include "os/poll_posix.h"
- #elif defined(OS_WINDOWS) || defined(OS_WINCE)
- #include "os/poll_windows.h"
 -/* OS event abstraction */
 -
 -int usbi_create_event(usbi_event_t *event);
 -void usbi_destroy_event(usbi_event_t *event);
 -void usbi_signal_event(usbi_event_t *event);
 -void usbi_clear_event(usbi_event_t *event);
 -
 -#ifdef HAVE_OS_TIMER
 -int usbi_create_timer(usbi_timer_t *timer);
 -void usbi_destroy_timer(usbi_timer_t *timer);
 -int usbi_arm_timer(usbi_timer_t *timer, const struct timespec *timeout);
 -int usbi_disarm_timer(usbi_timer_t *timer);
--#endif
--
- struct usbi_pollfd {
-       /* must come first */
-       struct libusb_pollfd pollfd;
 -static inline int usbi_using_timer(struct libusb_context *ctx)
 -{
 -#ifdef HAVE_OS_TIMER
 -      return usbi_timer_valid(&ctx->timer);
 -#else
 -      UNUSED(ctx);
 -      return 0;
 -#endif
 -}
--
-       struct list_head list;
 -struct usbi_reported_events {
 -      union {
 -              struct {
 -                      unsigned int event_triggered:1;
 -#ifdef HAVE_OS_TIMER
 -                      unsigned int timer_triggered:1;
 -#endif
 -              };
 -              unsigned int event_bits;
 -      };
 -      void *event_data;
 -      unsigned int event_data_count;
 -      unsigned int num_ready;
--};
--
- int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
- void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
 -int usbi_alloc_event_data(struct libusb_context *ctx);
 -int usbi_wait_for_events(struct libusb_context *ctx,
 -      struct usbi_reported_events *reported_events, int timeout_ms);
 -
 -/* accessor functions for structure private data */
 -
 -static inline void *usbi_get_context_priv(struct libusb_context *ctx)
 -{
 -      return (unsigned char *)ctx + PTR_ALIGN(sizeof(*ctx));
 -}
 -
 -static inline void *usbi_get_device_priv(struct libusb_device *dev)
 -{
 -      return (unsigned char *)dev + PTR_ALIGN(sizeof(*dev));
 -}
 -
 -static inline void *usbi_get_device_handle_priv(struct libusb_device_handle *dev_handle)
 -{
 -      return (unsigned char *)dev_handle + PTR_ALIGN(sizeof(*dev_handle));
 -}
 -
 -static inline void *usbi_get_transfer_priv(struct usbi_transfer *itransfer)
 -{
 -      return itransfer->priv;
 -}
--
--/* device discovery */
--
--/* we traverse usbfs without knowing how many devices we are going to find.
-- * so we create this discovered_devs model which is similar to a linked-list
-- * which grows when required. it can be freed once discovery has completed,
-- * eliminating the need for a list node in the libusb_device structure
-- * itself. */
--struct discovered_devs {
--      size_t len;
--      size_t capacity;
--      struct libusb_device *devices[ZERO_SIZED_ARRAY];
--};
--
--struct discovered_devs *discovered_devs_append(
--      struct discovered_devs *discdevs, struct libusb_device *dev);
--
--/* OS abstraction */
--
--/* This is the interface that OS backends need to implement.
-- * All fields are mandatory, except ones explicitly noted as optional. */
--struct usbi_os_backend {
--      /* A human-readable name for your backend, e.g. "Linux usbfs" */
--      const char *name;
--
--      /* Binary mask for backend specific capabilities */
--      uint32_t caps;
--
--      /* Perform initialization of your backend. You might use this function
--       * to determine specific capabilities of the system, allocate required
--       * data structures for later, etc.
--       *
--       * This function is called when a libusb user initializes the library
--       * prior to use.
--       *
--       * Return 0 on success, or a LIBUSB_ERROR code on failure.
--       */
--      int (*init)(struct libusb_context *ctx);
--
--      /* Deinitialization. Optional. This function should destroy anything
--       * that was set up by init.
--       *
--       * This function is called when the user deinitializes the library.
--       */
--      void (*exit)(struct libusb_context *ctx);
--
--      /* Set a backend-specific option. Optional.
--       *
--       * This function is called when the user calls libusb_set_option() and
--       * the option is not handled by the core library.
--       *
--       * Return 0 on success, or a LIBUSB_ERROR code on failure.
--       */
--      int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
--              va_list args);
--
--      /* Enumerate all the USB devices on the system, returning them in a list
--       * of discovered devices.
--       *
--       * Your implementation should enumerate all devices on the system,
--       * regardless of whether they have been seen before or not.
--       *
--       * When you have found a device, compute a session ID for it. The session
--       * ID should uniquely represent that particular device for that particular
--       * connection session since boot (i.e. if you disconnect and reconnect a
--       * device immediately after, it should be assigned a different session ID).
--       * If your OS cannot provide a unique session ID as described above,
--       * presenting a session ID of (bus_number << 8 | device_address) should
--       * be sufficient. Bus numbers and device addresses wrap and get reused,
--       * but that is an unlikely case.
--       *
--       * After computing a session ID for a device, call
--       * usbi_get_device_by_session_id(). This function checks if libusb already
--       * knows about the device, and if so, it provides you with a reference
--       * to a libusb_device structure for it.
--       *
--       * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
--       * a new device structure for the device. Call usbi_alloc_device() to
--       * obtain a new libusb_device structure with reference count 1. Populate
--       * the bus_number and device_address attributes of the new device, and
--       * perform any other internal backend initialization you need to do. At
--       * this point, you should be ready to provide device descriptors and so
--       * on through the get_*_descriptor functions. Finally, call
--       * usbi_sanitize_device() to perform some final sanity checks on the
--       * device. Assuming all of the above succeeded, we can now continue.
--       * If any of the above failed, remember to unreference the device that
--       * was returned by usbi_alloc_device().
--       *
--       * At this stage we have a populated libusb_device structure (either one
--       * that was found earlier, or one that we have just allocated and
--       * populated). This can now be added to the discovered devices list
--       * using discovered_devs_append(). Note that discovered_devs_append()
--       * may reallocate the list, returning a new location for it, and also
--       * note that reallocation can fail. Your backend should handle these
--       * error conditions appropriately.
--       *
--       * This function should not generate any bus I/O and should not block.
--       * If I/O is required (e.g. reading the active configuration value), it is
--       * OK to ignore these suggestions :)
--       *
--       * This function is executed when the user wishes to retrieve a list
--       * of USB devices connected to the system.
--       *
--       * If the backend has hotplug support, this function is not used!
--       *
--       * Return 0 on success, or a LIBUSB_ERROR code on failure.
--       */
--      int (*get_device_list)(struct libusb_context *ctx,
--              struct discovered_devs **discdevs);
--
--      /* Apps which were written before hotplug support, may listen for
--       * hotplug events on their own and call libusb_get_device_list on
--       * device addition. In this case libusb_get_device_list will likely
--       * return a list without the new device in there, as the hotplug
--       * event thread will still be busy enumerating the device, which may
--       * take a while, or may not even have seen the event yet.
--       *
--       * To avoid this libusb_get_device_list will call this optional
--       * function for backends with hotplug support before copying
--       * ctx->usb_devs to the user. In this function the backend should
--       * ensure any pending hotplug events are fully processed before
--       * returning.
--       *
--       * Optional, should be implemented by backends with hotplug support.
--       */
--      void (*hotplug_poll)(void);
 -
 -      /* Wrap a platform-specific device handle for I/O and other USB
 -       * operations. The device handle is preallocated for you.
 -       *
 -       * Your backend should allocate any internal resources required for I/O
 -       * and other operations so that those operations can happen (hopefully)
 -       * without hiccup. This is also a good place to inform libusb that it
 -       * should monitor certain file descriptors related to this device -
 -       * see the usbi_add_event_source() function.
 -       *
 -       * Your backend should also initialize the device structure
 -       * (dev_handle->dev), which is NULL at the beginning of the call.
 -       *
 -       * This function should not generate any bus I/O and should not block.
 -       *
 -       * This function is called when the user attempts to wrap an existing
 -       * platform-specific device handle for a device.
 -       *
 -       * Return:
 -       * - 0 on success
 -       * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
 -       * - another LIBUSB_ERROR code on other failure
 -       *
 -       * Do not worry about freeing the handle on failed open, the upper layers
 -       * do this for you.
 -       */
 -      int (*wrap_sys_device)(struct libusb_context *ctx,
 -              struct libusb_device_handle *dev_handle, intptr_t sys_dev);
--
--      /* Open a device for I/O and other USB operations. The device handle
--       * is preallocated for you, you can retrieve the device in question
--       * through handle->dev.
--       *
--       * Your backend should allocate any internal resources required for I/O
--       * and other operations so that those operations can happen (hopefully)
--       * without hiccup. This is also a good place to inform libusb that it
--       * should monitor certain file descriptors related to this device -
-        * see the usbi_add_pollfd() function.
 -       * see the usbi_add_event_source() function.
--       *
--       * This function should not generate any bus I/O and should not block.
--       *
--       * This function is called when the user attempts to obtain a device
--       * handle for a device.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
--       *   discovery
--       * - another LIBUSB_ERROR code on other failure
--       *
--       * Do not worry about freeing the handle on failed open, the upper layers
--       * do this for you.
--       */
--      int (*open)(struct libusb_device_handle *dev_handle);
--
--      /* Close a device such that the handle cannot be used again. Your backend
--       * should destroy any resources that were allocated in the open path.
-        * This may also be a good place to call usbi_remove_pollfd() to inform
-        * libusb of any file descriptors associated with this device that should
-        * no longer be monitored.
 -       * This may also be a good place to call usbi_remove_event_source() to
 -       * inform libusb of any event sources associated with this device that
 -       * should no longer be monitored.
--       *
--       * This function is called when the user closes a device handle.
--       */
--      void (*close)(struct libusb_device_handle *dev_handle);
-       /* Retrieve the device descriptor from a device.
-        *
-        * The descriptor should be retrieved from memory, NOT via bus I/O to the
-        * device. This means that you may have to cache it in a private structure
-        * during get_device_list enumeration. Alternatively, you may be able
-        * to retrieve it from a kernel interface (some Linux setups can do this)
-        * still without generating bus I/O.
-        *
-        * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
-        * buffer, which is guaranteed to be big enough.
-        *
-        * This function is called when sanity-checking a device before adding
-        * it to the list of discovered devices, and also when the user requests
-        * to read the device descriptor.
-        *
-        * This function is expected to return the descriptor in bus-endian format
-        * (LE). If it returns the multi-byte values in host-endian format,
-        * set the host_endian output parameter to "1".
-        *
-        * Return 0 on success or a LIBUSB_ERROR code on failure.
-        */
-       int (*get_device_descriptor)(struct libusb_device *device,
-               unsigned char *buffer, int *host_endian);
--
--      /* Get the ACTIVE configuration descriptor for a device.
--       *
--       * The descriptor should be retrieved from memory, NOT via bus I/O to the
--       * device. This means that you may have to cache it in a private structure
--       * during get_device_list enumeration. You may also have to keep track
--       * of which configuration is active when the user changes it.
--       *
--       * This function is expected to write len bytes of data into buffer, which
--       * is guaranteed to be big enough. If you can only do a partial write,
--       * return an error code.
--       *
--       * This function is expected to return the descriptor in bus-endian format
-        * (LE). If it returns the multi-byte values in host-endian format,
-        * set the host_endian output parameter to "1".
 -       * (LE).
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*get_active_config_descriptor)(struct libusb_device *device,
-               unsigned char *buffer, size_t len, int *host_endian);
 -              void *buffer, size_t len);
--
--      /* Get a specific configuration descriptor for a device.
--       *
--       * The descriptor should be retrieved from memory, NOT via bus I/O to the
--       * device. This means that you may have to cache it in a private structure
--       * during get_device_list enumeration.
--       *
--       * The requested descriptor is expressed as a zero-based index (i.e. 0
--       * indicates that we are requesting the first descriptor). The index does
--       * not (necessarily) equal the bConfigurationValue of the configuration
--       * being requested.
--       *
--       * This function is expected to write len bytes of data into buffer, which
--       * is guaranteed to be big enough. If you can only do a partial write,
--       * return an error code.
--       *
--       * This function is expected to return the descriptor in bus-endian format
-        * (LE). If it returns the multi-byte values in host-endian format,
-        * set the host_endian output parameter to "1".
 -       * (LE).
--       *
--       * Return the length read on success or a LIBUSB_ERROR code on failure.
--       */
--      int (*get_config_descriptor)(struct libusb_device *device,
-               uint8_t config_index, unsigned char *buffer, size_t len,
-               int *host_endian);
 -              uint8_t config_index, void *buffer, size_t len);
--
--      /* Like get_config_descriptor but then by bConfigurationValue instead
--       * of by index.
--       *
--       * Optional, if not present the core will call get_config_descriptor
--       * for all configs until it finds the desired bConfigurationValue.
--       *
--       * Returns a pointer to the raw-descriptor in *buffer, this memory
--       * is valid as long as device is valid.
--       *
--       * Returns the length of the returned raw-descriptor on success,
--       * or a LIBUSB_ERROR code on failure.
--       */
--      int (*get_config_descriptor_by_value)(struct libusb_device *device,
-               uint8_t bConfigurationValue, unsigned char **buffer,
-               int *host_endian);
 -              uint8_t bConfigurationValue, void **buffer);
--
--      /* Get the bConfigurationValue for the active configuration for a device.
--       * Optional. This should only be implemented if you can retrieve it from
--       * cache (don't generate I/O).
--       *
--       * If you cannot retrieve this from cache, either do not implement this
--       * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
--       * libusb to retrieve the information through a standard control transfer.
--       *
--       * This function must be non-blocking.
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
--       *   blocking
--       * - another LIBUSB_ERROR code on other failure.
--       */
-       int (*get_configuration)(struct libusb_device_handle *dev_handle, int *config);
 -      int (*get_configuration)(struct libusb_device_handle *dev_handle, uint8_t *config);
--
--      /* Set the active configuration for a device.
--       *
--       * A configuration value of -1 should put the device in unconfigured state.
--       *
--       * This function can block.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
--       * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
--       *   configuration cannot be changed)
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure.
--       */
--      int (*set_configuration)(struct libusb_device_handle *dev_handle, int config);
--
--      /* Claim an interface. When claimed, the application can then perform
--       * I/O to an interface's endpoints.
--       *
--       * This function should not generate any bus I/O and should not block.
--       * Interface claiming is a logical operation that simply ensures that
--       * no other drivers/applications are using the interface, and after
--       * claiming, no other drivers/applications can use the interface because
--       * we now "own" it.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
--       * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
-       int (*claim_interface)(struct libusb_device_handle *dev_handle, int interface_number);
 -      int (*claim_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
--
--      /* Release a previously claimed interface.
--       *
--       * This function should also generate a SET_INTERFACE control request,
--       * resetting the alternate setting of that interface to 0. It's OK for
--       * this function to block as a result.
--       *
--       * You will only ever be asked to release an interface which was
--       * successfully claimed earlier.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
-       int (*release_interface)(struct libusb_device_handle *dev_handle, int interface_number);
 -      int (*release_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
--
--      /* Set the alternate setting for an interface.
--       *
--       * You will only ever be asked to set the alternate setting for an
--       * interface which was successfully claimed earlier.
--       *
--       * It's OK for this function to block.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle,
-               int interface_number, int altsetting);
 -              uint8_t interface_number, uint8_t altsetting);
--
--      /* Clear a halt/stall condition on an endpoint.
--       *
--       * It's OK for this function to block.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*clear_halt)(struct libusb_device_handle *dev_handle,
--              unsigned char endpoint);
--
-       /* Perform a USB port reset to reinitialize a device.
 -      /* Perform a USB port reset to reinitialize a device. Optional.
--       *
--       * If possible, the device handle should still be usable after the reset
--       * completes, assuming that the device descriptors did not change during
--       * reset and all previous interface state can be restored.
--       *
-        * If something changes, or you cannot easily locate/verify the resetted
 -       * If something changes, or you cannot easily locate/verify the reset
--       * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
--       * to close the old handle and re-enumerate the device.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
--       *   has been disconnected since it was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*reset_device)(struct libusb_device_handle *dev_handle);
--
--      /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
--      int (*alloc_streams)(struct libusb_device_handle *dev_handle,
--              uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
--
--      /* Free usb3 bulk streams allocated with alloc_streams */
--      int (*free_streams)(struct libusb_device_handle *dev_handle,
--              unsigned char *endpoints, int num_endpoints);
--
--      /* Allocate persistent DMA memory for the given device, suitable for
--       * zerocopy. May return NULL on failure. Optional to implement.
--       */
-       unsigned char *(*dev_mem_alloc)(struct libusb_device_handle *handle,
-               size_t len);
 -      void *(*dev_mem_alloc)(struct libusb_device_handle *handle, size_t len);
--
--      /* Free memory allocated by dev_mem_alloc. */
-       int (*dev_mem_free)(struct libusb_device_handle *handle,
-               unsigned char *buffer, size_t len);
 -      int (*dev_mem_free)(struct libusb_device_handle *handle, void *buffer,
 -              size_t len);
--
--      /* Determine if a kernel driver is active on an interface. Optional.
--       *
--       * The presence of a kernel driver on an interface indicates that any
--       * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
--       *
--       * Return:
--       * - 0 if no driver is active
--       * - 1 if a driver is active
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*kernel_driver_active)(struct libusb_device_handle *dev_handle,
-               int interface_number);
 -              uint8_t interface_number);
--
--      /* Detach a kernel driver from an interface. Optional.
--       *
--       * After detaching a kernel driver, the interface should be available
--       * for claim.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
--       * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle,
-               int interface_number);
 -              uint8_t interface_number);
--
--      /* Attach a kernel driver to an interface. Optional.
--       *
--       * Reattach a kernel driver to the device.
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
--       * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
--       *   was opened
--       * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
--       *   preventing reattachment
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle,
-               int interface_number);
 -              uint8_t interface_number);
--
--      /* Destroy a device. Optional.
--       *
--       * This function is called when the last reference to a device is
--       * destroyed. It should free any resources allocated in the get_device_list
--       * path.
--       */
--      void (*destroy_device)(struct libusb_device *dev);
--
--      /* Submit a transfer. Your implementation should take the transfer,
--       * morph it into whatever form your platform requires, and submit it
--       * asynchronously.
--       *
--       * This function must not block.
--       *
--       * This function gets called with the flying_transfers_lock locked!
--       *
--       * Return:
--       * - 0 on success
--       * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
--       * - another LIBUSB_ERROR code on other failure
--       */
--      int (*submit_transfer)(struct usbi_transfer *itransfer);
--
--      /* Cancel a previously submitted transfer.
--       *
--       * This function must not block. The transfer cancellation must complete
--       * later, resulting in a call to usbi_handle_transfer_cancellation()
--       * from the context of handle_events.
--       */
--      int (*cancel_transfer)(struct usbi_transfer *itransfer);
--
--      /* Clear a transfer as if it has completed or cancelled, but do not
--       * report any completion/cancellation to the library. You should free
--       * all private data from the transfer as if you were just about to report
--       * completion or cancellation.
--       *
--       * This function might seem a bit out of place. It is used when libusb
--       * detects a disconnected device - it calls this function for all pending
--       * transfers before reporting completion (with the disconnect code) to
--       * the user. Maybe we can improve upon this internal interface in future.
--       */
--      void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
--
-       /* Handle any pending events on file descriptors. Optional.
 -      /* Handle any pending events on event sources. Optional.
--       *
-        * Provide this function when file descriptors directly indicate device
-        * or transfer activity. If your backend does not have such file descriptors,
 -       * Provide this function when event sources directly indicate device
 -       * or transfer activity. If your backend does not have such event sources,
--       * implement the handle_transfer_completion function below.
--       *
--       * This involves monitoring any active transfers and processing their
--       * completion or cancellation.
--       *
-        * The function is passed an array of pollfd structures (size nfds)
-        * as a result of the poll() system call. The num_ready parameter
-        * indicates the number of file descriptors that have reported events
-        * (i.e. the poll() return value). This should be enough information
-        * for you to determine which actions need to be taken on the currently
-        * active transfers.
 -       * The function is passed a pointer that represents platform-specific
 -       * data for monitoring event sources (size count). This data is to be
 -       * (re)allocated as necessary when event sources are modified.
 -       * The num_ready parameter indicates the number of event sources that
 -       * have reported events. This should be enough information for you to
 -       * determine which actions need to be taken on the currently active
 -       * transfers.
--       *
--       * For any cancelled transfers, call usbi_handle_transfer_cancellation().
--       * For completed transfers, call usbi_handle_transfer_completion().
--       * For control/bulk/interrupt transfers, populate the "transferred"
--       * element of the appropriate usbi_transfer structure before calling the
--       * above functions. For isochronous transfers, populate the status and
--       * transferred fields of the iso packet descriptors of the transfer.
--       *
--       * This function should also be able to detect disconnection of the
--       * device, reporting that situation with usbi_handle_disconnect().
--       *
--       * When processing an event related to a transfer, you probably want to
--       * take usbi_transfer.lock to prevent races. See the documentation for
--       * the usbi_transfer structure.
--       *
--       * Return 0 on success, or a LIBUSB_ERROR code on failure.
--       */
--      int (*handle_events)(struct libusb_context *ctx,
-               struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready);
 -              void *event_data, unsigned int count, unsigned int num_ready);
--
--      /* Handle transfer completion. Optional.
--       *
-        * Provide this function when there are no file descriptors available
-        * that directly indicate device or transfer activity. If your backend does
-        * have such file descriptors, implement the handle_events function above.
 -       * Provide this function when there are no event sources available that
 -       * directly indicate device or transfer activity. If your backend does
 -       * have such event sources, implement the handle_events function above.
--       *
--       * Your backend must tell the library when a transfer has completed by
--       * calling usbi_signal_transfer_completion(). You should store any private
--       * information about the transfer and its completion status in the transfer's
--       * private backend data.
--       *
--       * During event handling, this function will be called on each transfer for
--       * which usbi_signal_transfer_completion() was called.
--       *
--       * For any cancelled transfers, call usbi_handle_transfer_cancellation().
--       * For completed transfers, call usbi_handle_transfer_completion().
--       * For control/bulk/interrupt transfers, populate the "transferred"
--       * element of the appropriate usbi_transfer structure before calling the
--       * above functions. For isochronous transfers, populate the status and
--       * transferred fields of the iso packet descriptors of the transfer.
--       *
--       * Return 0 on success, or a LIBUSB_ERROR code on failure.
--       */
--      int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
-       /* Get time from specified clock. At least two clocks must be implemented
-          by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
-          Description of clocks:
-            USBI_CLOCK_REALTIME : clock returns time since system epoch.
-            USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
-                                    time (usually boot).
-        */
-       int (*clock_gettime)(int clkid, struct timespec *tp);
- #ifdef USBI_TIMERFD_AVAILABLE
-       /* clock ID of the clock that should be used for timerfd */
-       clockid_t (*get_timerfd_clockid)(void);
- #endif
--
--      /* Number of bytes to reserve for per-context private backend data.
-        * This private data area is accessible through the "os_priv" field of
-        * struct libusb_context. */
 -       * This private data area is accessible by calling
 -       * usbi_get_context_priv() on the libusb_context instance.
 -       */
--      size_t context_priv_size;
--
--      /* Number of bytes to reserve for per-device private backend data.
-        * This private data area is accessible through the "os_priv" field of
-        * struct libusb_device. */
 -       * This private data area is accessible by calling
 -       * usbi_get_device_priv() on the libusb_device instance.
 -       */
--      size_t device_priv_size;
--
--      /* Number of bytes to reserve for per-handle private backend data.
-        * This private data area is accessible through the "os_priv" field of
-        * struct libusb_device. */
 -       * This private data area is accessible by calling
 -       * usbi_get_device_handle_priv() on the libusb_device_handle instance.
 -       */
--      size_t device_handle_priv_size;
--
--      /* Number of bytes to reserve for per-transfer private backend data.
--       * This private data area is accessible by calling
-        * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
 -       * usbi_get_transfer_priv() on the usbi_transfer instance.
--       */
--      size_t transfer_priv_size;
--};
--
--extern const struct usbi_os_backend usbi_backend;
--
- extern struct list_head active_contexts_list;
- extern usbi_mutex_static_t active_contexts_lock;
 -#define for_each_context(c) \
 -      for_each_helper(c, &active_contexts_list, struct libusb_context)
 -
 -#define for_each_device(ctx, d) \
 -      for_each_helper(d, &(ctx)->usb_devs, struct libusb_device)
 -
 -#define for_each_device_safe(ctx, d, n) \
 -      for_each_safe_helper(d, n, &(ctx)->usb_devs, struct libusb_device)
 -
 -#define for_each_open_device(ctx, h) \
 -      for_each_helper(h, &(ctx)->open_devs, struct libusb_device_handle)
 -
 -#define __for_each_transfer(list, t) \
 -      for_each_helper(t, (list), struct usbi_transfer)
 -
 -#define for_each_transfer(ctx, t) \
 -      __for_each_transfer(&(ctx)->flying_transfers, t)
 -
 -#define __for_each_transfer_safe(list, t, n) \
 -      for_each_safe_helper(t, n, (list), struct usbi_transfer)
 -
 -#define for_each_transfer_safe(ctx, t, n) \
 -      __for_each_transfer_safe(&(ctx)->flying_transfers, t, n)
 -
 -#define __for_each_completed_transfer_safe(list, t, n) \
 -      list_for_each_entry_safe(t, n, (list), completed_list, struct usbi_transfer)
 -
 -#define for_each_event_source(ctx, e) \
 -      for_each_helper(e, &(ctx)->event_sources, struct usbi_event_source)
 -
 -#define for_each_removed_event_source(ctx, e) \
 -      for_each_helper(e, &(ctx)->removed_event_sources, struct usbi_event_source)
 -
 -#define for_each_removed_event_source_safe(ctx, e, n) \
 -      for_each_safe_helper(e, n, &(ctx)->removed_event_sources, struct usbi_event_source)
--
--#ifdef __cplusplus
--}
--#endif
--
--#endif
diff --cc mac/libusb/os/darwin_usb.c
index 35ea1c321e7215f13dadd329a7bcbdc4da5e9c16,e415589d670f071e6acb03247ba7b448fdb1e096..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2142 -1,2302 +1,0 @@@
--/* -*- Mode: C; indent-tabs-mode:nil -*- */
--/*
-- * darwin backend for libusb 1.0
-  * Copyright © 2008-2017 Nathan Hjelm <hjelmn@users.sourceforge.net>
 - * Copyright © 2008-2020 Nathan Hjelm <hjelmn@cs.unm.edu>
 - * Copyright © 2019-2020 Google LLC. All rights reserved.
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
- #include "config.h"
 -#include <config.h>
 -#include <assert.h>
--#include <time.h>
--#include <ctype.h>
- #include <errno.h>
--#include <pthread.h>
--#include <stdio.h>
--#include <stdlib.h>
--#include <string.h>
--#include <sys/types.h>
--#include <unistd.h>
--#include <fcntl.h>
--#include <sys/sysctl.h>
--
--#include <mach/clock.h>
--#include <mach/clock_types.h>
--#include <mach/mach_host.h>
--#include <mach/mach_port.h>
--
--/* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
-- * function. Its use is also conditionalized to only older deployment targets. */
--#define OBJC_SILENCE_GC_DEPRECATIONS 1
--
--#include <AvailabilityMacros.h>
--#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
--  #include <objc/objc-auto.h>
- #endif
- #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
- /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
- #include <stdatomic.h>
- #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
- _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
- #else
- /* use darwin atomics if the target is older than 10.12 */
- #include <libkern/OSAtomic.h>
- /* OSAtomicAdd32Barrier returns the new value */
- #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
- static volatile int32_t initCount = 0;
- #endif
- /* On 10.12 and later, use newly available clock_*() functions */
- #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
- #define OSX_USE_CLOCK_GETTIME 1
- #else
- #define OSX_USE_CLOCK_GETTIME 0
--#endif
--
--#include "darwin_usb.h"
 -
 -static pthread_mutex_t libusb_darwin_init_mutex = PTHREAD_MUTEX_INITIALIZER;
 -static int init_count = 0;
--
--/* async event thread */
--static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
--static pthread_cond_t  libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
- static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
--
- #if !OSX_USE_CLOCK_GETTIME
 -#if !defined(HAVE_CLOCK_GETTIME)
--static clock_serv_t clock_realtime;
--static clock_serv_t clock_monotonic;
--#endif
 -
 -#define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
--
--static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
--static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
--
--static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
- static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
- static const char *darwin_device_class = kIOUSBDeviceClassName;
 -static struct list_head darwin_cached_devices;
 -static const char *darwin_device_class = "IOUSBDevice";
--
- #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
 -#define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
--
--/* async event thread */
--static pthread_t libusb_darwin_at;
--
- static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
- static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
- static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
 -static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
 -static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
 -static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
--static int darwin_reset_device(struct libusb_device_handle *dev_handle);
--static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
--
- static int darwin_scan_devices(struct libusb_context *ctx);
- static int process_new_device (struct libusb_context *ctx, io_service_t service);
 -static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
 -static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
 -                                             UInt64 old_session_id);
 -
 -static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
 -                                                  UInt64 *old_session_id);
--
--#if defined(ENABLE_LOGGING)
- static const char *darwin_error_str (int result) {
 -static const char *darwin_error_str (IOReturn result) {
--  static char string_buffer[50];
--  switch (result) {
--  case kIOReturnSuccess:
--    return "no error";
--  case kIOReturnNotOpen:
--    return "device not opened for exclusive access";
--  case kIOReturnNoDevice:
--    return "no connection to an IOService";
--  case kIOUSBNoAsyncPortErr:
--    return "no async port has been opened for interface";
--  case kIOReturnExclusiveAccess:
--    return "another process has device opened for exclusive access";
--  case kIOUSBPipeStalled:
--    return "pipe is stalled";
--  case kIOReturnError:
--    return "could not establish a connection to the Darwin kernel";
--  case kIOUSBTransactionTimeout:
--    return "transaction timed out";
--  case kIOReturnBadArgument:
--    return "invalid argument";
--  case kIOReturnAborted:
--    return "transaction aborted";
--  case kIOReturnNotResponding:
--    return "device not responding";
--  case kIOReturnOverrun:
--    return "data overrun";
--  case kIOReturnCannotWire:
--    return "physical memory can not be wired down";
--  case kIOReturnNoResources:
--    return "out of resources";
--  case kIOUSBHighSpeedSplitError:
--    return "high speed split error";
 -  case kIOUSBUnknownPipeErr:
 -    return "pipe ref not recognized";
--  default:
--    snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
--    return string_buffer;
--  }
--}
--#endif
--
- static int darwin_to_libusb (int result) {
 -static enum libusb_error darwin_to_libusb (IOReturn result) {
--  switch (result) {
--  case kIOReturnUnderrun:
--  case kIOReturnSuccess:
--    return LIBUSB_SUCCESS;
--  case kIOReturnNotOpen:
--  case kIOReturnNoDevice:
--    return LIBUSB_ERROR_NO_DEVICE;
--  case kIOReturnExclusiveAccess:
--    return LIBUSB_ERROR_ACCESS;
--  case kIOUSBPipeStalled:
--    return LIBUSB_ERROR_PIPE;
--  case kIOReturnBadArgument:
--    return LIBUSB_ERROR_INVALID_PARAM;
--  case kIOUSBTransactionTimeout:
--    return LIBUSB_ERROR_TIMEOUT;
--  case kIOReturnNotResponding:
--  case kIOReturnAborted:
--  case kIOReturnError:
--  case kIOUSBNoAsyncPortErr:
 -  case kIOUSBUnknownPipeErr:
--  default:
--    return LIBUSB_ERROR_OTHER;
--  }
--}
--
--/* this function must be called with the darwin_cached_devices_lock held */
--static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
--  cached_dev->refcount--;
--  /* free the device and remove it from the cache */
--  if (0 == cached_dev->refcount) {
--    list_del(&cached_dev->list);
--
-     (*(cached_dev->device))->Release(cached_dev->device);
 -    if (cached_dev->device) {
 -      (*(cached_dev->device))->Release(cached_dev->device);
 -      cached_dev->device = NULL;
 -    }
--    free (cached_dev);
--  }
--}
--
--static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
--  cached_dev->refcount++;
--}
--
--static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--
--  /* current interface */
--  struct darwin_interface *cInterface;
--
-   int8_t i, iface;
 -  uint8_t i, iface;
--
--  usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
--
--  for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
--    cInterface = &priv->interfaces[iface];
--
-     if (dev_handle->claimed_interfaces & (1 << iface)) {
 -    if (dev_handle->claimed_interfaces & (1U << iface)) {
--      for (i = 0 ; i < cInterface->num_endpoints ; i++) {
--        if (cInterface->endpoint_addrs[i] == ep) {
--          *pipep = i + 1;
--
--          if (ifcp)
--            *ifcp = iface;
--
--          if (interface_out)
--            *interface_out = cInterface;
--
--          usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
-           return 0;
 -          return LIBUSB_SUCCESS;
--        }
--      }
--    }
--  }
--
--  /* No pipe found with the correct endpoint address */
--  usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
--
--  return LIBUSB_ERROR_NOT_FOUND;
--}
--
- static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
 -static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
--  CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
--
--  if (!matchingDict)
--    return kIOReturnError;
--
--  if (location) {
--    CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
--                                                                         &kCFTypeDictionaryKeyCallBacks,
--                                                                         &kCFTypeDictionaryValueCallBacks);
--
--    /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
--         internally (CFNumberType of locationID is kCFNumberSInt32Type) */
--    CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
--
--    if (propertyMatchDict && locationCF) {
--      CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
--      CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
--    }
--    /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
--
--    /* release our references as per the Create Rule */
--    if (propertyMatchDict)
--      CFRelease (propertyMatchDict);
--    if (locationCF)
--      CFRelease (locationCF);
--  }
--
--  return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
--}
--
--/* Returns 1 on success, 0 on failure. */
- static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
 -static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
--  CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
-   int ret = 0;
 -  Boolean success = 0;
--
--  if (cfNumber) {
--    if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
-       ret = CFNumberGetValue(cfNumber, type, p);
 -      success = CFNumberGetValue(cfNumber, type, p);
--    }
--
--    CFRelease (cfNumber);
--  }
--
-   return ret;
 -  return (success != 0);
--}
--
- static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
 -/* Returns 1 on success, 0 on failure. */
 -static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
--  CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
-   int ret = 0;
 -  bool success = false;
--
--  if (cfData) {
--    if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
--      CFIndex length = CFDataGetLength (cfData);
--      if (length < size) {
--        size = length;
--      }
--
--      CFDataGetBytes (cfData, CFRangeMake(0, size), p);
-       ret = 1;
 -      success = true;
--    }
--
--    CFRelease (cfData);
--  }
--
-   return ret;
 -  return success;
--}
--
--static usb_device_t **darwin_device_from_service (io_service_t service)
--{
--  io_cf_plugin_ref_t *plugInInterface = NULL;
--  usb_device_t **device;
-   kern_return_t result;
 -  IOReturn kresult;
--  SInt32 score;
 -  const int max_retries = 5;
--
-   result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
-                                              kIOCFPlugInInterfaceID, &plugInInterface,
-                                              &score);
 -  /* The IOCreatePlugInInterfaceForService function might consistently return
 -     an "out of resources" error with certain USB devices the first time we run 
 -     it. The reason is still unclear, but retrying fixes the problem */
 -  for (int count = 0; count < max_retries; count++) {
 -    kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
 -                                                kIOCFPlugInInterfaceID, &plugInInterface,
 -                                                &score);
 -    if (kIOReturnSuccess == kresult && plugInInterface) {
 -      break;
 -    }
--
-   if (kIOReturnSuccess != result || !plugInInterface) {
-     usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
 -    usbi_dbg ("set up plugin for service retry: %s", darwin_error_str (kresult));
 -
 -    /* sleep for a little while before trying again */
 -    nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 1000}, NULL);
 -  }
 -
 -  if (kIOReturnSuccess != kresult || !plugInInterface) {
 -    usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
--    return NULL;
--  }
--
--  (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
--                                           (LPVOID)&device);
--  /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
--  (*plugInInterface)->Release (plugInInterface);
--
--  return device;
--}
--
--static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
--  UNUSED(ptr);
 -  struct darwin_cached_device *cached_device;
 -  UInt64 old_session_id;
--  struct libusb_context *ctx;
--  io_service_t service;
 -  int ret;
--
--  usbi_mutex_lock(&active_contexts_lock);
--
--  while ((service = IOIteratorNext(add_devices))) {
 -    ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
 -    if (ret < 0 || !cached_device->can_enumerate) {
 -      continue;
 -    }
 -
--    /* add this device to each active context's device list */
-     list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
-       process_new_device (ctx, service);
 -    for_each_context(ctx) {
 -      process_new_device (ctx, cached_device, old_session_id);
 -    }
 -
 -    if (cached_device->in_reenumerate) {
 -      usbi_dbg ("cached device in reset state. reset complete...");
 -      cached_device->in_reenumerate = false;
--    }
--
--    IOObjectRelease(service);
--  }
--
--  usbi_mutex_unlock(&active_contexts_lock);
--}
--
--static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
--  UNUSED(ptr);
--  struct libusb_device *dev = NULL;
--  struct libusb_context *ctx;
--  struct darwin_cached_device *old_device;
--
--  io_service_t device;
--  UInt64 session;
--  int ret;
--
--  usbi_mutex_lock(&active_contexts_lock);
--
--  while ((device = IOIteratorNext (rem_devices)) != 0) {
 -    bool is_reenumerating = false;
 -
--    /* get the location from the i/o registry */
--    ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
--    IOObjectRelease (device);
--    if (!ret)
--      continue;
--
--    /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
--       otherwise no cached device will ever get freed */
--    usbi_mutex_lock(&darwin_cached_devices_lock);
--    list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
--      if (old_device->session == session) {
-         darwin_deref_cached_device (old_device);
 -        if (old_device->in_reenumerate) {
 -          /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
 -           * will deref if needed. */
 -          usbi_dbg ("detected device detached due to re-enumeration");
 -
 -          /* the device object is no longer usable so go ahead and release it */
 -          if (old_device->device) {
 -            (*(old_device->device))->Release(old_device->device);
 -            old_device->device = NULL;
 -          }
 -
 -          is_reenumerating = true;
 -        } else {
 -          darwin_deref_cached_device (old_device);
 -        }
 -
--        break;
--      }
--    }
 -
--    usbi_mutex_unlock(&darwin_cached_devices_lock);
 -    if (is_reenumerating) {
 -      continue;
 -    }
--
-     list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
 -    for_each_context(ctx) {
--      usbi_dbg ("notifying context %p of device disconnect", ctx);
--
--      dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
--      if (dev) {
--        /* signal the core that this device has been disconnected. the core will tear down this device
--           when the reference count reaches 0 */
--        usbi_disconnect_device(dev);
--        libusb_unref_device(dev);
--      }
--    }
--  }
--
--  usbi_mutex_unlock(&active_contexts_lock);
--}
--
--static void darwin_hotplug_poll (void)
--{
-   /* not sure if 5 seconds will be too long/short but it should work ok */
-   mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
 -  /* not sure if 1 ms will be too long/short but it should work ok */
 -  mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
--
-   /* since a kernel thread may nodify the IOInterators used for
-    * hotplug notidication we can't just clear the iterators.
 -  /* since a kernel thread may notify the IOIterators used for
 -   * hotplug notification we can't just clear the iterators.
--   * instead just wait until all IOService providers are quiet */
--  (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
--}
--
--static void darwin_clear_iterator (io_iterator_t iter) {
--  io_service_t device;
--
--  while ((device = IOIteratorNext (iter)) != 0)
--    IOObjectRelease (device);
 -}
 -
 -static void darwin_fail_startup(void) {
 -  pthread_mutex_lock (&libusb_darwin_at_mutex);
 -  libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
 -  pthread_cond_signal (&libusb_darwin_at_cond);
 -  pthread_mutex_unlock (&libusb_darwin_at_mutex);
 -  pthread_exit (NULL);
--}
--
--static void *darwin_event_thread_main (void *arg0) {
--  IOReturn kresult;
--  struct libusb_context *ctx = (struct libusb_context *)arg0;
--  CFRunLoopRef runloop;
 -  CFRunLoopSourceRef libusb_shutdown_cfsource;
 -  CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
--
--#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
--  /* Set this thread's name, so it can be seen in the debugger
--     and crash reports. */
--  pthread_setname_np ("org.libusb.device-hotplug");
--#endif
--
--#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
--  /* Tell the Objective-C garbage collector about this thread.
--     This is required because, unlike NSThreads, pthreads are
--     not automatically registered. Although we don't use
--     Objective-C, we use CoreFoundation, which does.
--     Garbage collection support was entirely removed in 10.12,
--     so don't bother there. */
--  objc_registerThreadWithCollector();
--#endif
--
--  /* hotplug (device arrival/removal) sources */
-   CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
--  CFRunLoopSourceRef     libusb_notification_cfsource;
--  io_notification_port_t libusb_notification_port;
--  io_iterator_t          libusb_rem_device_iterator;
--  io_iterator_t          libusb_add_device_iterator;
--
--  usbi_dbg ("creating hotplug event source");
--
--  runloop = CFRunLoopGetCurrent ();
--  CFRetain (runloop);
--
--  /* add the shutdown cfsource to the run loop */
--  memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
--  libusb_shutdown_cfsourcectx.info = runloop;
--  libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
-   libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
-   CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
 -  libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
 -  CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
--
--  /* add the notification port to the run loop */
--  libusb_notification_port     = IONotificationPortCreate (kIOMasterPortDefault);
--  libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
--  CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
--
--  /* create notifications for removed devices */
--  kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
--                                              IOServiceMatching(darwin_device_class),
--                                              darwin_devices_detached,
--                                              ctx, &libusb_rem_device_iterator);
--
--  if (kresult != kIOReturnSuccess) {
--    usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
-     pthread_exit (NULL);
 -    CFRelease (libusb_shutdown_cfsource);
 -    CFRelease (runloop);
 -    darwin_fail_startup ();
--  }
--
--  /* create notifications for attached devices */
--  kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
--                                              IOServiceMatching(darwin_device_class),
--                                              darwin_devices_attached,
--                                              ctx, &libusb_add_device_iterator);
--
--  if (kresult != kIOReturnSuccess) {
--    usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
-     pthread_exit (NULL);
 -    CFRelease (libusb_shutdown_cfsource);
 -    CFRelease (runloop);
 -    darwin_fail_startup ();
--  }
--
--  /* arm notifiers */
--  darwin_clear_iterator (libusb_rem_device_iterator);
--  darwin_clear_iterator (libusb_add_device_iterator);
--
--  usbi_dbg ("darwin event thread ready to receive events");
--
--  /* signal the main thread that the hotplug runloop has been created. */
--  pthread_mutex_lock (&libusb_darwin_at_mutex);
--  libusb_darwin_acfl = runloop;
 -  libusb_darwin_acfls = libusb_shutdown_cfsource;
--  pthread_cond_signal (&libusb_darwin_at_cond);
--  pthread_mutex_unlock (&libusb_darwin_at_mutex);
--
--  /* run the runloop */
--  CFRunLoopRun();
--
--  usbi_dbg ("darwin event thread exiting");
 -
 -  /* signal the main thread that the hotplug runloop has finished. */
 -  pthread_mutex_lock (&libusb_darwin_at_mutex);
 -  libusb_darwin_acfls = NULL;
 -  libusb_darwin_acfl = NULL;
 -  pthread_cond_signal (&libusb_darwin_at_cond);
 -  pthread_mutex_unlock (&libusb_darwin_at_mutex);
--
--  /* remove the notification cfsource */
--  CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
--
--  /* remove the shutdown cfsource */
-   CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
 -  CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
--
--  /* delete notification port */
--  IONotificationPortDestroy (libusb_notification_port);
--
--  /* delete iterators */
--  IOObjectRelease (libusb_rem_device_iterator);
--  IOObjectRelease (libusb_add_device_iterator);
--
-   CFRelease (libusb_darwin_acfls);
 -  CFRelease (libusb_shutdown_cfsource);
--  CFRelease (runloop);
-   libusb_darwin_acfls = NULL;
-   libusb_darwin_acfl = NULL;
--
--  pthread_exit (NULL);
--}
--
--/* cleanup function to destroy cached devices */
- static void __attribute__((destructor)) _darwin_finalize(void) {
 -static void darwin_cleanup_devices(void) {
--  struct darwin_cached_device *dev, *next;
--
-   usbi_mutex_lock(&darwin_cached_devices_lock);
--  list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
--    darwin_deref_cached_device(dev);
--  }
-   usbi_mutex_unlock(&darwin_cached_devices_lock);
- }
- static void darwin_check_version (void) {
-   /* adjust for changes in the USB stack in xnu 15 */
-   int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
-   long version;
-   char version_string[256] = {'\0',};
-   size_t length = 256;
-   sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
--
-   errno = 0;
-   version = strtol (version_string, NULL, 10);
-   if (0 == errno && version >= 15) {
-     darwin_device_class = "IOUSBHostDevice";
-   }
 -  darwin_cached_devices.prev = darwin_cached_devices.next = NULL;
--}
--
--static int darwin_init(struct libusb_context *ctx) {
 -  bool first_init;
--  int rc;
--
-   rc = pthread_once (&darwin_init_once, darwin_check_version);
-   if (rc) {
-     return LIBUSB_ERROR_OTHER;
-   }
 -  pthread_mutex_lock (&libusb_darwin_init_mutex);
--
-   rc = darwin_scan_devices (ctx);
-   if (LIBUSB_SUCCESS != rc) {
-     return rc;
-   }
 -  first_init = (1 == ++init_count);
--
-   if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
- #if !OSX_USE_CLOCK_GETTIME
-     /* create the clocks that will be used if clock_gettime() is not available */
-     host_name_port_t host_self;
 -  do {
 -    if (first_init) {
 -      assert (NULL == darwin_cached_devices.next);
 -      list_init (&darwin_cached_devices);
--
-     host_self = mach_host_self();
-     host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
-     host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
-     mach_port_deallocate(mach_task_self(), host_self);
 -#if !defined(HAVE_CLOCK_GETTIME)
 -      /* create the clocks that will be used if clock_gettime() is not available */
 -      host_name_port_t host_self;
 -
 -      host_self = mach_host_self();
 -      host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
 -      host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
 -      mach_port_deallocate(mach_task_self(), host_self);
--#endif
 -    }
--
-     pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
 -    rc = darwin_scan_devices (ctx);
 -    if (LIBUSB_SUCCESS != rc)
 -      break;
--
-     pthread_mutex_lock (&libusb_darwin_at_mutex);
-     while (!libusb_darwin_acfl)
-       pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
-     pthread_mutex_unlock (&libusb_darwin_at_mutex);
 -    if (first_init) {
 -      rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
 -      if (0 != rc) {
 -        usbi_err (ctx, "could not create event thread, error %d", rc);
 -        rc = LIBUSB_ERROR_OTHER;
 -        break;
 -      }
 -
 -      pthread_mutex_lock (&libusb_darwin_at_mutex);
 -      while (!libusb_darwin_acfl)
 -        pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
 -      if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
 -        libusb_darwin_acfl = NULL;
 -        rc = LIBUSB_ERROR_OTHER;
 -      }
 -      pthread_mutex_unlock (&libusb_darwin_at_mutex);
 -
 -      if (0 != rc)
 -        pthread_join (libusb_darwin_at, NULL);
 -    }
 -  } while (0);
 -
 -  if (LIBUSB_SUCCESS != rc) {
 -    if (first_init) {
 -      darwin_cleanup_devices ();
 -#if !defined(HAVE_CLOCK_GETTIME)
 -      mach_port_deallocate(mach_task_self(), clock_realtime);
 -      mach_port_deallocate(mach_task_self(), clock_monotonic);
 -#endif
 -    }
 -    --init_count;
--  }
 -
 -  pthread_mutex_unlock (&libusb_darwin_init_mutex);
--
--  return rc;
--}
--
--static void darwin_exit (struct libusb_context *ctx) {
--  UNUSED(ctx);
-   if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
- #if !OSX_USE_CLOCK_GETTIME
-     mach_port_deallocate(mach_task_self(), clock_realtime);
-     mach_port_deallocate(mach_task_self(), clock_monotonic);
- #endif
 -
 -  pthread_mutex_lock (&libusb_darwin_init_mutex);
--
 -  if (0 == --init_count) {
--    /* stop the event runloop and wait for the thread to terminate. */
-     CFRunLoopSourceSignal(libusb_darwin_acfls);
 -    pthread_mutex_lock (&libusb_darwin_at_mutex);
 -    CFRunLoopSourceSignal (libusb_darwin_acfls);
--    CFRunLoopWakeUp (libusb_darwin_acfl);
 -    while (libusb_darwin_acfl)
 -      pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
 -    pthread_mutex_unlock (&libusb_darwin_at_mutex);
--    pthread_join (libusb_darwin_at, NULL);
-   }
- }
- static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
-   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
--
-   /* return cached copy */
-   memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
 -    darwin_cleanup_devices ();
--
-   *host_endian = 0;
 -#if !defined(HAVE_CLOCK_GETTIME)
 -    mach_port_deallocate(mach_task_self(), clock_realtime);
 -    mach_port_deallocate(mach_task_self(), clock_monotonic);
 -#endif
 -  }
--
-   return 0;
 -  pthread_mutex_unlock (&libusb_darwin_init_mutex);
--}
--
- static int get_configuration_index (struct libusb_device *dev, int config_value) {
 -static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
--  struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
--  UInt8 i, numConfig;
--  IOUSBConfigurationDescriptorPtr desc;
--  IOReturn kresult;
--
--  /* is there a simpler way to determine the index? */
--  kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
--  if (kresult != kIOReturnSuccess)
--    return darwin_to_libusb (kresult);
--
--  for (i = 0 ; i < numConfig ; i++) {
--    (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
--
--    if (desc->bConfigurationValue == config_value)
--      return i;
--  }
--
--  /* configuration not found */
--  return LIBUSB_ERROR_NOT_FOUND;
--}
--
- static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
 -static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
--  struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
--  int config_index;
--
--  if (0 == priv->active_config)
--    return LIBUSB_ERROR_NOT_FOUND;
--
--  config_index = get_configuration_index (dev, priv->active_config);
--  if (config_index < 0)
--    return config_index;
--
-   return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
 -  assert(config_index >= 0 && config_index <= UINT8_MAX);
 -  return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
--}
--
- static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
 -static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
--  struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
--  IOUSBConfigurationDescriptorPtr desc;
--  IOReturn kresult;
--  int ret;
--
--  if (!priv || !priv->device)
--    return LIBUSB_ERROR_OTHER;
--
--  kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
--  if (kresult == kIOReturnSuccess) {
--    /* copy descriptor */
--    if (libusb_le16_to_cpu(desc->wTotalLength) < len)
--      len = libusb_le16_to_cpu(desc->wTotalLength);
--
--    memmove (buffer, desc, len);
-     /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
-     *host_endian = 0;
--  }
--
--  ret = darwin_to_libusb (kresult);
--  if (ret != LIBUSB_SUCCESS)
--    return ret;
--
--  return (int) len;
--}
--
--/* check whether the os has configured the device */
- static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
 -static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
--  usb_device_t **darwin_device = dev->device;
--
--  IOUSBConfigurationDescriptorPtr configDesc;
--  IOUSBFindInterfaceRequest request;
-   kern_return_t             kresult;
 -  IOReturn                  kresult;
--  io_iterator_t             interface_iterator;
--  io_service_t              firstInterface;
--
--  if (dev->dev_descriptor.bNumConfigurations < 1) {
--    usbi_err (ctx, "device has no configurations");
--    return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
--  }
--
--  /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
--     not usable anyway */
-   if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
 -  if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
 -      0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
--    usbi_dbg ("ignoring configuration on root hub simulation");
--    dev->active_config = 0;
-     return 0;
 -    return LIBUSB_SUCCESS;
--  }
--
--  /* find the first configuration */
--  kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
--  dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
--
--  /* check if the device is already configured. there is probably a better way than iterating over the
--     to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
--     might lock up on the device request) */
--
--  /* Setup the Interface Request */
--  request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
--  request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
--  request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
--  request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
--
--  kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
-   if (kresult)
 -  if (kresult != kIOReturnSuccess)
--    return darwin_to_libusb (kresult);
--
--  /* iterate once */
--  firstInterface = IOIteratorNext(interface_iterator);
--
--  /* done with the interface iterator */
--  IOObjectRelease(interface_iterator);
--
--  if (firstInterface) {
--    IOObjectRelease (firstInterface);
--
--    /* device is configured */
--    if (dev->dev_descriptor.bNumConfigurations == 1)
--      /* to avoid problems with some devices get the configurations value from the configuration descriptor */
--      dev->active_config = dev->first_config;
--    else
--      /* devices with more than one configuration should work with GetConfiguration */
--      (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
--  } else
--    /* not configured */
--    dev->active_config = 0;
-   
 -
--  usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
--
-   return 0;
 -  return LIBUSB_SUCCESS;
--}
--
- static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
 -static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
--  IOUSBDevRequestTO req;
 -
 -  assert(buffer_size <= UINT16_MAX);
--
--  memset (buffer, 0, buffer_size);
--
--  /* Set up request for descriptor/ */
--  req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
--  req.bRequest      = kUSBRqGetDescriptor;
-   req.wValue        = desc << 8;
 -  req.wValue        = (UInt16)(desc << 8);
--  req.wIndex        = desc_index;
-   req.wLength       = buffer_size;
 -  req.wLength       = (UInt16)buffer_size;
--  req.pData         = buffer;
--  req.noDataTimeout = 20;
--  req.completionTimeout = 100;
--
--  return (*device)->DeviceRequestTO (device, &req);
--}
--
- static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
 -static enum libusb_error darwin_cache_device_descriptor (struct darwin_cached_device *dev) {
--  usb_device_t **device = dev->device;
-   int retries = 1, delay = 30000;
 -  int retries = 1;
 -  long delay = 30000; // microseconds
--  int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
--  int is_open = 0;
-   int ret = 0, ret2;
 -  IOReturn ret = 0, ret2;
--  UInt8 bDeviceClass;
--  UInt16 idProduct, idVendor;
--
--  dev->can_enumerate = 0;
--
--  (*device)->GetDeviceClass (device, &bDeviceClass);
--  (*device)->GetDeviceProduct (device, &idProduct);
--  (*device)->GetDeviceVendor (device, &idVendor);
--
--  /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
--   * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request.  Still,
--   * to follow the spec as closely as possible, try opening the device */
--  is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
--
--  do {
--    /**** retrieve device descriptor ****/
--    ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
--
--    if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
--      /* received an overrun error but we still received a device descriptor */
--      ret = kIOReturnSuccess;
--
--    if (kIOUSBVendorIDAppleComputer == idVendor) {
--      /* NTH: don't bother retrying or unsuspending Apple devices */
--      break;
--    }
--
--    if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
--                                    0 == dev->dev_descriptor.bcdUSB)) {
--      /* work around for incorrectly configured devices */
--      if (try_reconfigure && is_open) {
--        usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
--
--        /* set the first configuration */
--        (*device)->SetConfiguration(device, 1);
--
--        /* don't try to reconfigure again */
--        try_reconfigure = 0;
--      }
--
--      ret = kIOUSBPipeStalled;
--    }
--
--    if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
--      /* device may be suspended. unsuspend it and try again */
--#if DeviceVersion >= 320
--      UInt32 info = 0;
--
--      /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
--      (void)(*device)->GetUSBDeviceInformation (device, &info);
--
--      /* note that the device was suspended */
-       if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
 -      if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
--        try_unsuspend = 1;
--#endif
--
--      if (try_unsuspend) {
--        /* try to unsuspend the device */
--        ret2 = (*device)->USBDeviceSuspend (device, 0);
--        if (kIOReturnSuccess != ret2) {
--          /* prevent log spew from poorly behaving devices.  this indicates the
--             os actually had trouble communicating with the device */
--          usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
--        } else
--          unsuspended = 1;
--
--        try_unsuspend = 0;
--      }
--    }
--
--    if (kIOReturnSuccess != ret) {
-       usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
 -      usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
--      /* sleep for a little while before trying again */
-       nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
 -      nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
--    }
--  } while (kIOReturnSuccess != ret && retries--);
--
--  if (unsuspended)
--    /* resuspend the device */
--    (void)(*device)->USBDeviceSuspend (device, 1);
--
--  if (is_open)
--    (void) (*device)->USBDeviceClose (device);
--
--  if (ret != kIOReturnSuccess) {
--    /* a debug message was already printed out for this error */
--    if (LIBUSB_CLASS_HUB == bDeviceClass)
--      usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
--                idVendor, idProduct, darwin_error_str (ret), ret);
--    else
-       usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
 -      usbi_warn (NULL, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
--                 idVendor, idProduct, darwin_error_str (ret), ret);
--    return darwin_to_libusb (ret);
--  }
--
--  /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
--  if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
--    /* not a valid device */
-     usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
 -    usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
--               idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
--    return LIBUSB_ERROR_NO_DEVICE;
--  }
--
--  usbi_dbg ("cached device descriptor:");
--  usbi_dbg ("  bDescriptorType:    0x%02x", dev->dev_descriptor.bDescriptorType);
-   usbi_dbg ("  bcdUSB:             0x%04x", dev->dev_descriptor.bcdUSB);
 -  usbi_dbg ("  bcdUSB:             0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
--  usbi_dbg ("  bDeviceClass:       0x%02x", dev->dev_descriptor.bDeviceClass);
--  usbi_dbg ("  bDeviceSubClass:    0x%02x", dev->dev_descriptor.bDeviceSubClass);
--  usbi_dbg ("  bDeviceProtocol:    0x%02x", dev->dev_descriptor.bDeviceProtocol);
--  usbi_dbg ("  bMaxPacketSize0:    0x%02x", dev->dev_descriptor.bMaxPacketSize0);
-   usbi_dbg ("  idVendor:           0x%04x", dev->dev_descriptor.idVendor);
-   usbi_dbg ("  idProduct:          0x%04x", dev->dev_descriptor.idProduct);
-   usbi_dbg ("  bcdDevice:          0x%04x", dev->dev_descriptor.bcdDevice);
 -  usbi_dbg ("  idVendor:           0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
 -  usbi_dbg ("  idProduct:          0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
 -  usbi_dbg ("  bcdDevice:          0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
--  usbi_dbg ("  iManufacturer:      0x%02x", dev->dev_descriptor.iManufacturer);
--  usbi_dbg ("  iProduct:           0x%02x", dev->dev_descriptor.iProduct);
--  usbi_dbg ("  iSerialNumber:      0x%02x", dev->dev_descriptor.iSerialNumber);
--  usbi_dbg ("  bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
--
--  dev->can_enumerate = 1;
--
--  return LIBUSB_SUCCESS;
--}
--
- static int get_device_port (io_service_t service, UInt8 *port) {
-   kern_return_t result;
 -/* Returns 1 on success, 0 on failure. */
 -static bool get_device_port (io_service_t service, UInt8 *port) {
 -  IOReturn kresult;
--  io_service_t parent;
-   int ret = 0;
 -  bool ret = false;
--
--  if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
-     return 1;
 -    return true;
--  }
--
-   result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
-   if (kIOReturnSuccess == result) {
 -  kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
 -  if (kIOReturnSuccess == kresult) {
--    ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
--    IOObjectRelease (parent);
--  }
--
--  return ret;
--}
--
- static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
-   kern_return_t result;
 -/* Returns 1 on success, 0 on failure. */
 -static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
 -  IOReturn kresult;
--  io_service_t parent;
--
--  /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
--  parent = service;
-   while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
 -  while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
--    if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
--        /* Success */
-         return 1;
 -        return true;
--    }
--  }
--
--  /* We ran out of parents */
-   return 0;
 -  return false;
--}
--
- static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
-                                     struct darwin_cached_device **cached_out) {
 -static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
 -                                                  UInt64 *old_session_id) {
--  struct darwin_cached_device *new_device;
--  UInt64 sessionID = 0, parent_sessionID = 0;
-   int ret = LIBUSB_SUCCESS;
 -  UInt32 locationID = 0;
 -  enum libusb_error ret = LIBUSB_SUCCESS;
--  usb_device_t **device;
--  UInt8 port = 0;
 -
 -  /* assuming sessionID != 0 normally (never seen it be 0) */
 -  *old_session_id = 0;
 -  *cached_out = NULL;
--
--  /* get some info from the io registry */
--  (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
 -  (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
--  if (!get_device_port (service, &port)) {
--    usbi_dbg("could not get connected port number");
--  }
--
--  usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
--
--  if (get_device_parent_sessionID(service, &parent_sessionID)) {
--    usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
--  }
--
--  usbi_mutex_lock(&darwin_cached_devices_lock);
--  do {
-     *cached_out = NULL;
--    list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
-       usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
 -      usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
 -               sessionID, locationID, new_device->session, new_device->location);
 -      if (new_device->location == locationID && new_device->in_reenumerate) {
 -        usbi_dbg ("found cached device with matching location that is being re-enumerated");
 -        *old_session_id = new_device->session;
 -        break;
 -      }
 -
--      if (new_device->session == sessionID) {
--        usbi_dbg("using cached device for device");
--        *cached_out = new_device;
--        break;
--      }
--    }
--
--    if (*cached_out)
--      break;
--
--    usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
--
--    device = darwin_device_from_service (service);
--    if (!device) {
--      ret = LIBUSB_ERROR_NO_DEVICE;
--      break;
--    }
--
-     new_device = calloc (1, sizeof (*new_device));
-     if (!new_device) {
-       ret = LIBUSB_ERROR_NO_MEM;
-       break;
-     }
 -    if (!(*old_session_id)) {
 -      new_device = calloc (1, sizeof (*new_device));
 -      if (!new_device) {
 -        ret = LIBUSB_ERROR_NO_MEM;
 -        break;
 -      }
--
-     /* add this device to the cached device list */
-     list_add(&new_device->list, &darwin_cached_devices);
 -      /* add this device to the cached device list */
 -      list_add(&new_device->list, &darwin_cached_devices);
--
-     (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
 -      (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
--
-     /* keep a reference to this device */
-     darwin_ref_cached_device(new_device);
 -      /* keep a reference to this device */
 -      darwin_ref_cached_device(new_device);
--
-     new_device->device = device;
 -      (*device)->GetLocationID (device, &new_device->location);
 -      new_device->port = port;
 -      new_device->parent_session = parent_sessionID;
 -    }
 -
 -    /* keep track of devices regardless of if we successfully enumerate them to
 -       prevent them from being enumerated multiple times */
 -    *cached_out = new_device;
 -
--    new_device->session = sessionID;
-     (*device)->GetLocationID (device, &new_device->location);
-     new_device->port = port;
-     new_device->parent_session = parent_sessionID;
 -    new_device->device = device;
--
--    /* cache the device descriptor */
-     ret = darwin_cache_device_descriptor(ctx, new_device);
 -    ret = darwin_cache_device_descriptor(new_device);
--    if (ret)
--      break;
--
--    if (new_device->can_enumerate) {
--      snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
-                new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
 -               libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
 -               libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
--               new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
--    }
--  } while (0);
--
--  usbi_mutex_unlock(&darwin_cached_devices_lock);
-   /* keep track of devices regardless of if we successfully enumerate them to
-      prevent them from being enumerated multiple times */
-   *cached_out = new_device;
--
--  return ret;
--}
--
- static int process_new_device (struct libusb_context *ctx, io_service_t service) {
 -static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
 -                                             UInt64 old_session_id) {
--  struct darwin_device_priv *priv;
--  struct libusb_device *dev = NULL;
-   struct darwin_cached_device *cached_device;
--  UInt8 devSpeed;
-   int ret = 0;
 -  enum libusb_error ret = LIBUSB_SUCCESS;
--
--  do {
-     ret = darwin_get_cached_device (ctx, service, &cached_device);
-     if (ret < 0 || !cached_device->can_enumerate) {
-       return ret;
-     }
--    /* check current active configuration (and cache the first configuration value--
--       which may be used by claim_interface) */
--    ret = darwin_check_configuration (ctx, cached_device);
--    if (ret)
--      break;
--
-     usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
-               ctx, cached_device->session);
 -    if (0 != old_session_id) {
 -      usbi_dbg ("re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
 -                ctx, old_session_id, cached_device->session);
 -      /* save the libusb device before the session id is updated */
 -      dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
 -    }
--
-     dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
--    if (!dev) {
-       return LIBUSB_ERROR_NO_MEM;
-     }
 -      usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
 -                ctx, cached_device->session);
--
-     priv = (struct darwin_device_priv *)dev->os_priv;
 -      dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
 -      if (!dev) {
 -        return LIBUSB_ERROR_NO_MEM;
 -      }
--
-     priv->dev = cached_device;
-     darwin_ref_cached_device (priv->dev);
 -      priv = usbi_get_device_priv(dev);
 -
 -      priv->dev = cached_device;
 -      darwin_ref_cached_device (priv->dev);
 -      dev->port_number    = cached_device->port;
 -      dev->bus_number     = cached_device->location >> 24;
 -      assert(cached_device->address <= UINT8_MAX);
 -      dev->device_address = (uint8_t)cached_device->address;
 -    } else {
 -      priv = usbi_get_device_priv(dev);
 -    }
 -
 -    static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
 -                  "mismatch between libusb and IOKit device descriptor sizes");
 -    memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
 -    usbi_localize_device_descriptor(&dev->device_descriptor);
 -    dev->session_data = cached_device->session;
--
--    if (cached_device->parent_session > 0) {
--      dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
--    } else {
--      dev->parent_dev = NULL;
--    }
-     dev->port_number    = cached_device->port;
-     dev->bus_number     = cached_device->location >> 24;
-     dev->device_address = cached_device->address;
--
--    (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
--
--    switch (devSpeed) {
--    case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
--    case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
--    case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
--#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
--    case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
--#endif
--#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
--    case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
--#endif
--    default:
--      usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
--    }
--
--    ret = usbi_sanitize_device (dev);
--    if (ret < 0)
--      break;
--
--    usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
--              dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
 -
--  } while (0);
--
-   if (0 == ret) {
 -  if (!cached_device->in_reenumerate && 0 == ret) {
--    usbi_connect_device (dev);
--  } else {
--    libusb_unref_device (dev);
--  }
--
--  return ret;
--}
--
- static int darwin_scan_devices(struct libusb_context *ctx) {
 -static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
 -  struct darwin_cached_device *cached_device;
 -  UInt64 old_session_id;
--  io_iterator_t deviceIterator;
--  io_service_t service;
-   kern_return_t kresult;
 -  IOReturn kresult;
 -  int ret;
--
--  kresult = usb_setup_device_iterator (&deviceIterator, 0);
--  if (kresult != kIOReturnSuccess)
--    return darwin_to_libusb (kresult);
--
--  while ((service = IOIteratorNext (deviceIterator))) {
-     (void) process_new_device (ctx, service);
 -    ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
 -    if (ret < 0 || !cached_device->can_enumerate) {
 -      continue;
 -    }
 -
 -    (void) process_new_device (ctx, cached_device, old_session_id);
--
--    IOObjectRelease(service);
--  }
--
--  IOObjectRelease(deviceIterator);
--
-   return 0;
 -  return LIBUSB_SUCCESS;
--}
--
--static int darwin_open (struct libusb_device_handle *dev_handle) {
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
--  IOReturn kresult;
--
--  if (0 == dpriv->open_count) {
--    /* try to open the device */
--    kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
--    if (kresult != kIOReturnSuccess) {
--      usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
--
--      if (kIOReturnExclusiveAccess != kresult) {
--        return darwin_to_libusb (kresult);
--      }
--
--      /* it is possible to perform some actions on a device that is not open so do not return an error */
-       priv->is_open = 0;
 -      priv->is_open = false;
--    } else {
-       priv->is_open = 1;
 -      priv->is_open = true;
--    }
--
--    /* create async event source */
--    kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
--    if (kresult != kIOReturnSuccess) {
--      usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
--
--      if (priv->is_open) {
--        (*(dpriv->device))->USBDeviceClose (dpriv->device);
--      }
--
-       priv->is_open = 0;
 -      priv->is_open = false;
--
--      return darwin_to_libusb (kresult);
--    }
--
--    CFRetain (libusb_darwin_acfl);
--
--    /* add the cfSource to the aync run loop */
--    CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
--  }
--
--  /* device opened successfully */
--  dpriv->open_count++;
--
--  usbi_dbg ("device open for access");
--
--  return 0;
--}
--
--static void darwin_close (struct libusb_device_handle *dev_handle) {
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
--  IOReturn kresult;
--  int i;
--
--  if (dpriv->open_count == 0) {
--    /* something is probably very wrong if this is the case */
--    usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
--    return;
--  }
--
--  dpriv->open_count--;
--
--  /* make sure all interfaces are released */
--  for (i = 0 ; i < USB_MAXINTERFACES ; i++)
-     if (dev_handle->claimed_interfaces & (1 << i))
 -    if (dev_handle->claimed_interfaces & (1U << i))
--      libusb_release_interface (dev_handle, i);
--
--  if (0 == dpriv->open_count) {
--    /* delete the device's async event source */
--    if (priv->cfSource) {
--      CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
--      CFRelease (priv->cfSource);
--      priv->cfSource = NULL;
--      CFRelease (libusb_darwin_acfl);
--    }
--
--    if (priv->is_open) {
--      /* close the device */
--      kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
-       if (kresult) {
 -      if (kresult != kIOReturnSuccess) {
--        /* Log the fact that we had a problem closing the file, however failing a
--         * close isn't really an error, so return success anyway */
--        usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
--      }
--    }
--  }
--}
--
- static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
 -static int darwin_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config) {
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
--
-   *config = (int) dpriv->active_config;
 -  *config = dpriv->active_config;
--
-   return 0;
 -  return LIBUSB_SUCCESS;
--}
--
- static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
 -static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
--  IOReturn kresult;
-   int i;
 -  uint8_t i;
 -
 -  if (config == -1)
 -    config = 0;
--
--  /* Setting configuration will invalidate the interface, so we need
--     to reclaim it. First, dispose of existing interfaces, if any. */
--  for (i = 0 ; i < USB_MAXINTERFACES ; i++)
-     if (dev_handle->claimed_interfaces & (1 << i))
 -    if (dev_handle->claimed_interfaces & (1U << i))
--      darwin_release_interface (dev_handle, i);
--
-   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
 -  kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
--  if (kresult != kIOReturnSuccess)
--    return darwin_to_libusb (kresult);
--
--  /* Reclaim any interfaces. */
--  for (i = 0 ; i < USB_MAXINTERFACES ; i++)
-     if (dev_handle->claimed_interfaces & (1 << i))
 -    if (dev_handle->claimed_interfaces & (1U << i))
--      darwin_claim_interface (dev_handle, i);
--
-   dpriv->active_config = config;
 -  dpriv->active_config = (UInt8)config;
--
-   return 0;
 -  return LIBUSB_SUCCESS;
--}
--
- static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
 -static IOReturn darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
--  IOUSBFindInterfaceRequest request;
-   kern_return_t             kresult;
 -  IOReturn                  kresult;
--  io_iterator_t             interface_iterator;
--  UInt8                     bInterfaceNumber;
-   int                       ret;
 -  bool                      ret;
--
--  *usbInterfacep = IO_OBJECT_NULL;
--
--  /* Setup the Interface Request */
--  request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
--  request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
--  request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
--  request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
--
--  kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
-   if (kresult)
 -  if (kresult != kIOReturnSuccess)
--    return kresult;
--
--  while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
--    /* find the interface number */
--    ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
--                                       &bInterfaceNumber);
--
--    if (ret && bInterfaceNumber == ifc) {
--      break;
--    }
--
--    (void) IOObjectRelease (*usbInterfacep);
--  }
--
--  /* done with the interface iterator */
--  IOObjectRelease(interface_iterator);
--
-   return 0;
 -  return kIOReturnSuccess;
--}
--
- static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, uint8_t iface) {
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--
--  /* current interface */
--  struct darwin_interface *cInterface = &priv->interfaces[iface];
--
-   kern_return_t kresult;
 -  IOReturn kresult;
--
--  UInt8 numep, direction, number;
--  UInt8 dont_care1, dont_care3;
--  UInt16 dont_care2;
--  int rc;
--
--  usbi_dbg ("building table of endpoints.");
--
--  /* retrieve the total number of endpoints on this interface */
--  kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
-   if (kresult) {
 -  if (kresult != kIOReturnSuccess) {
--    usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
--    return darwin_to_libusb (kresult);
--  }
--
--  /* iterate through pipe references */
-   for (int i = 1 ; i <= numep ; i++) {
 -  for (UInt8 i = 1 ; i <= numep ; i++) {
--    kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
--                                                            &dont_care2, &dont_care3);
--
--    if (kresult != kIOReturnSuccess) {
--      /* probably a buggy device. try to get the endpoint address from the descriptors */
--      struct libusb_config_descriptor *config;
--      const struct libusb_endpoint_descriptor *endpoint_desc;
--      UInt8 alt_setting;
--
--      kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
-       if (kresult) {
 -      if (kresult != kIOReturnSuccess) {
--        usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
--        return darwin_to_libusb (kresult);
--      }
--
--      rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
--      if (LIBUSB_SUCCESS != rc) {
--        return rc;
--      }
--
--      endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
--
--      cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
--    } else {
-       cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
 -      cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
--    }
--
--    usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
--              cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
--  }
--
--  cInterface->num_endpoints = numep;
--
-   return 0;
 -  return LIBUSB_SUCCESS;
--}
--
- static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
 -static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--  io_service_t          usbInterface = IO_OBJECT_NULL;
-   IOReturn kresult;
 -  IOReturn              kresult;
 -  enum libusb_error     ret;
--  IOCFPlugInInterface **plugInInterface = NULL;
--  SInt32                score;
--
--  /* current interface */
--  struct darwin_interface *cInterface = &priv->interfaces[iface];
--
--  kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
--  if (kresult != kIOReturnSuccess)
--    return darwin_to_libusb (kresult);
--
--  /* make sure we have an interface */
--  if (!usbInterface && dpriv->first_config != 0) {
--    usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
--
--    /* set the configuration */
-     kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
-     if (kresult != LIBUSB_SUCCESS) {
 -    ret = darwin_set_configuration (dev_handle, (int) dpriv->first_config);
 -    if (ret != LIBUSB_SUCCESS) {
--      usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
-       return kresult;
 -      return ret;
--    }
--
--    kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
-     if (kresult) {
 -    if (kresult != kIOReturnSuccess) {
--      usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
--      return darwin_to_libusb (kresult);
--    }
--  }
--
--  if (!usbInterface) {
--    usbi_err (HANDLE_CTX (dev_handle), "interface not found");
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
--  /* get an interface to the device's interface */
--  kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
--                                               kIOCFPlugInInterfaceID, &plugInInterface, &score);
--
--  /* ignore release error */
--  (void)IOObjectRelease (usbInterface);
--
-   if (kresult) {
 -  if (kresult != kIOReturnSuccess) {
--    usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
--    return darwin_to_libusb (kresult);
--  }
--
--  if (!plugInInterface) {
--    usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
--  /* Do the actual claim */
--  kresult = (*plugInInterface)->QueryInterface(plugInInterface,
-                                                CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
 -                                               CFUUIDGetUUIDBytes(InterfaceInterfaceID),
--                                               (LPVOID)&cInterface->interface);
--  /* We no longer need the intermediate plug-in */
--  /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
--  (*plugInInterface)->Release (plugInInterface);
-   if (kresult || !cInterface->interface) {
 -  if (kresult != kIOReturnSuccess || !cInterface->interface) {
--    usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
--    return darwin_to_libusb (kresult);
--  }
--
--  /* claim the interface */
--  kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
-   if (kresult) {
 -  if (kresult != kIOReturnSuccess) {
--    usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
--    return darwin_to_libusb (kresult);
--  }
--
--  /* update list of endpoints */
-   kresult = get_endpoints (dev_handle, iface);
-   if (kresult) {
 -  ret = get_endpoints (dev_handle, iface);
 -  if (ret) {
--    /* this should not happen */
--    darwin_release_interface (dev_handle, iface);
--    usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
-     return kresult;
 -    return ret;
--  }
--
--  cInterface->cfSource = NULL;
--
--  /* create async event source */
--  kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
--  if (kresult != kIOReturnSuccess) {
--    usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
--
--    /* can't continue without an async event source */
--    (void)darwin_release_interface (dev_handle, iface);
--
--    return darwin_to_libusb (kresult);
--  }
--
--  /* add the cfSource to the async thread's run loop */
--  CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
--
--  usbi_dbg ("interface opened");
--
-   return 0;
 -  return LIBUSB_SUCCESS;
--}
--
- static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--  IOReturn kresult;
--
--  /* current interface */
--  struct darwin_interface *cInterface = &priv->interfaces[iface];
--
--  /* Check to see if an interface is open */
--  if (!cInterface->interface)
--    return LIBUSB_SUCCESS;
--
--  /* clean up endpoint data */
--  cInterface->num_endpoints = 0;
--
--  /* delete the interface's async event source */
--  if (cInterface->cfSource) {
--    CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
--    CFRelease (cInterface->cfSource);
--  }
--
--  kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
-   if (kresult)
 -  if (kresult != kIOReturnSuccess)
--    usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
--
--  kresult = (*(cInterface->interface))->Release(cInterface->interface);
--  if (kresult != kIOReturnSuccess)
--    usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
--
--  cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
--
--  return darwin_to_libusb (kresult);
--}
--
- static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
-   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 -static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting) {
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
--  IOReturn kresult;
 -  enum libusb_error ret;
--
--  /* current interface */
--  struct darwin_interface *cInterface = &priv->interfaces[iface];
--
--  if (!cInterface->interface)
--    return LIBUSB_ERROR_NO_DEVICE;
--
--  kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
--  if (kresult != kIOReturnSuccess)
--    darwin_reset_device (dev_handle);
--
--  /* update list of endpoints */
-   kresult = get_endpoints (dev_handle, iface);
-   if (kresult) {
 -  ret = get_endpoints (dev_handle, iface);
 -  if (ret) {
--    /* this should not happen */
--    darwin_release_interface (dev_handle, iface);
--    usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
-     return kresult;
 -    return ret;
--  }
--
--  return darwin_to_libusb (kresult);
--}
--
--static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
--  /* current interface */
--  struct darwin_interface *cInterface;
--  IOReturn kresult;
--  uint8_t pipeRef;
--
--  /* determine the interface/endpoint to use */
--  if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
--    usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
--
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
--  /* newer versions of darwin support clearing additional bits on the device's endpoint */
--  kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
-   if (kresult)
 -  if (kresult != kIOReturnSuccess)
--    usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
--
--  return darwin_to_libusb (kresult);
 -}
 -
 -static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
 -                                 unsigned long claimed_interfaces) {
 -  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
 -  struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
 -  int open_count = dpriv->open_count;
 -  int ret;
 -
 -  /* clear claimed interfaces temporarily */
 -  dev_handle->claimed_interfaces = 0;
 -
 -  /* close and re-open the device */
 -  priv->is_open = false;
 -  dpriv->open_count = 1;
 -
 -  /* clean up open interfaces */
 -  (void) darwin_close (dev_handle);
 -
 -  /* re-open the device */
 -  ret = darwin_open (dev_handle);
 -  dpriv->open_count = open_count;
 -  if (LIBUSB_SUCCESS != ret) {
 -    /* could not restore configuration */
 -    return LIBUSB_ERROR_NOT_FOUND;
 -  }
 -
 -  if (dpriv->active_config != active_config) {
 -    usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
 -
 -    ret = darwin_set_configuration (dev_handle, active_config);
 -    if (LIBUSB_SUCCESS != ret) {
 -      usbi_dbg ("darwin/restore_state: could not restore configuration");
 -      return LIBUSB_ERROR_NOT_FOUND;
 -    }
 -  }
 -
 -  usbi_dbg ("darwin/restore_state: reclaiming interfaces");
 -
 -  if (claimed_interfaces) {
 -    for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
 -      if (!(claimed_interfaces & (1U << iface))) {
 -        continue;
 -      }
 -
 -      usbi_dbg ("darwin/restore_state: re-claiming interface %u", iface);
 -
 -      ret = darwin_claim_interface (dev_handle, iface);
 -      if (LIBUSB_SUCCESS != ret) {
 -        usbi_dbg ("darwin/restore_state: could not claim interface %u", iface);
 -        return LIBUSB_ERROR_NOT_FOUND;
 -      }
 -
 -      dev_handle->claimed_interfaces |= 1U << iface;
 -    }
 -  }
 -
 -  usbi_dbg ("darwin/restore_state: device state restored");
 -
 -  return LIBUSB_SUCCESS;
--}
--
--static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
 -  unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
 -  int8_t active_config = dpriv->active_config;
--  IOUSBDeviceDescriptor descriptor;
--  IOUSBConfigurationDescriptorPtr cached_configuration;
-   IOUSBConfigurationDescriptor configuration;
-   bool reenumerate = false;
 -  IOUSBConfigurationDescriptor *cached_configurations;
--  IOReturn kresult;
-   int i;
 -  UInt8 i;
--
-   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
-   if (kresult) {
-     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
-     return darwin_to_libusb (kresult);
 -  if (dpriv->in_reenumerate) {
 -    /* ack, two (or more) threads are trying to reset the device! abort! */
 -    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
-   do {
-     usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
 -  dpriv->in_reenumerate = true;
--
-     /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
-     (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
 -  /* store copies of descriptors so they can be compared after the reset */
 -  memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
 -  cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
--
-     /* check if the device descriptor has changed */
-     if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
-       reenumerate = true;
-       break;
-     }
 -  for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
 -    (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
 -    memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
 -  }
--
-     /* check if any configuration descriptor has changed */
-     for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
-       usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
 -  /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
 -  kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
 -  if (kresult != kIOReturnSuccess) {
 -    usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
 -    dpriv->in_reenumerate = false;
 -    return darwin_to_libusb (kresult);
 -  }
--
-       (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
-       (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
 -  usbi_dbg ("darwin/reset_device: waiting for re-enumeration to complete...");
--
-       if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
-         reenumerate = true;
-         break;
-       }
-     }
-   } while (0);
 -  while (dpriv->in_reenumerate) {
 -    struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
 -    nanosleep (&delay, NULL);
 -  }
--
-   if (reenumerate) {
-     usbi_dbg ("darwin/reset_device: device requires reenumeration");
-     (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
 -  /* compare descriptors */
 -  usbi_dbg ("darwin/reset_device: checking whether descriptors changed");
 -
 -  if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
 -    /* device descriptor changed. need to return not found. */
 -    usbi_dbg ("darwin/reset_device: device descriptor changed");
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
-   usbi_dbg ("darwin/reset_device: device reset complete");
 -  for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
 -    (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
 -    if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
 -      usbi_dbg ("darwin/reset_device: configuration descriptor %d changed", i);
 -      return LIBUSB_ERROR_NOT_FOUND;
 -    }
 -  }
--
-   return LIBUSB_SUCCESS;
 -  usbi_dbg ("darwin/reset_device: device reset complete. restoring state...");
 -
 -  return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
--}
--
- static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
 -static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
--  io_service_t usbInterface;
--  CFTypeRef driver;
--  IOReturn kresult;
--
--  kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
-   if (kresult) {
 -  if (kresult != kIOReturnSuccess) {
--    usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
--
--    return darwin_to_libusb (kresult);
--  }
--
--  driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
--  IOObjectRelease (usbInterface);
--
--  if (driver) {
--    CFRelease (driver);
--
--    return 1;
--  }
--
--  /* no driver */
--  return 0;
- }
- /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
- static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
-   UNUSED(dev_handle);
-   UNUSED(interface);
-   return LIBUSB_ERROR_NOT_SUPPORTED;
- }
- static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
-   UNUSED(dev_handle);
-   UNUSED(interface);
-   return LIBUSB_ERROR_NOT_SUPPORTED;
--}
--
--static void darwin_destroy_device(struct libusb_device *dev) {
-   struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
 -  struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
--
--  if (dpriv->dev) {
--    /* need to hold the lock in case this is the last reference to the device */
--    usbi_mutex_lock(&darwin_cached_devices_lock);
--    darwin_deref_cached_device (dpriv->dev);
--    dpriv->dev = NULL;
--    usbi_mutex_unlock(&darwin_cached_devices_lock);
--  }
--}
--
--static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--
--  IOReturn               ret;
--  uint8_t                transferType;
-   /* None of the values below are used in libusbx for bulk transfers */
-   uint8_t                direction, number, interval, pipeRef;
 -  uint8_t                pipeRef;
--  uint16_t               maxPacketSize;
--
--  struct darwin_interface *cInterface;
 -#if InterfaceVersion >= 550
 -  IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
 -#else
 -  /* None of the values below are used in libusb for bulk transfers */
 -  uint8_t                 direction, number, interval;
 -#endif
--
--  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
--    usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
--
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
 -
 -#if InterfaceVersion >= 550
 -  ret = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
--
 -  transferType = pipeProperties.bTransferType;
 -  maxPacketSize = pipeProperties.wMaxPacketSize;
 -#else
--  ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
--                                                       &transferType, &maxPacketSize, &interval);
 -#endif
--
--  if (ret) {
--    usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
--              darwin_error_str(ret), ret);
--    return darwin_to_libusb (ret);
--  }
--
--  if (0 != (transfer->length % maxPacketSize)) {
--    /* do not need a zero packet */
--    transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
--  }
--
--  /* submit the request */
--  /* timeouts are unavailable on interrupt endpoints */
--  if (transferType == kUSBInterrupt) {
--    if (IS_XFERIN(transfer))
--      ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
-                                                       transfer->length, darwin_async_io_callback, itransfer);
 -                                                      (UInt32)transfer->length, darwin_async_io_callback, itransfer);
--    else
--      ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
-                                                        transfer->length, darwin_async_io_callback, itransfer);
 -                                                       (UInt32)transfer->length, darwin_async_io_callback, itransfer);
--  } else {
--    itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
--
--    if (IS_XFERIN(transfer))
--      ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
-                                                         transfer->length, transfer->timeout, transfer->timeout,
-                                                         darwin_async_io_callback, (void *)itransfer);
 -                                                        (UInt32)transfer->length, transfer->timeout, transfer->timeout,
 -                                                        darwin_async_io_callback, itransfer);
--    else
--      ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
-                                                          transfer->length, transfer->timeout, transfer->timeout,
-                                                          darwin_async_io_callback, (void *)itransfer);
 -                                                         (UInt32)transfer->length, transfer->timeout, transfer->timeout,
 -                                                         darwin_async_io_callback, itransfer);
--  }
--
--  if (ret)
--    usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
--               darwin_error_str(ret), ret);
--
--  return darwin_to_libusb (ret);
--}
--
--#if InterfaceVersion >= 550
--static int submit_stream_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--  struct darwin_interface *cInterface;
--  uint8_t pipeRef;
--  IOReturn ret;
--
--  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
--    usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
--
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
--  itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
--
--  if (IS_XFERIN(transfer))
--    ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
-                                                              transfer->buffer, transfer->length, transfer->timeout,
-                                                              transfer->timeout, darwin_async_io_callback, (void *)itransfer);
 -                                                             transfer->buffer, (UInt32)transfer->length, transfer->timeout,
 -                                                             transfer->timeout, darwin_async_io_callback, itransfer);
--  else
--    ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
-                                                               transfer->buffer, transfer->length, transfer->timeout,
-                                                               transfer->timeout, darwin_async_io_callback, (void *)itransfer);
 -                                                              transfer->buffer, (UInt32)transfer->length, transfer->timeout,
 -                                                              transfer->timeout, darwin_async_io_callback, itransfer);
--
--  if (ret)
--    usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
--               darwin_error_str(ret), ret);
--
--  return darwin_to_libusb (ret);
--}
--#endif
--
--static int submit_iso_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
 -  struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
--
--  IOReturn kresult;
--  uint8_t direction, number, interval, pipeRef, transferType;
--  uint16_t maxPacketSize;
--  UInt64 frame;
--  AbsoluteTime atTime;
--  int i;
--
--  struct darwin_interface *cInterface;
--
-   /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
-   if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
 -  /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
 -  if (tpriv->num_iso_packets != transfer->num_iso_packets) {
--    free(tpriv->isoc_framelist);
--    tpriv->isoc_framelist = NULL;
--  }
--
--  if (!tpriv->isoc_framelist) {
--    tpriv->num_iso_packets = transfer->num_iso_packets;
-     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
 -    tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
--    if (!tpriv->isoc_framelist)
--      return LIBUSB_ERROR_NO_MEM;
--  }
--
--  /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
-   for (i = 0 ; i < transfer->num_iso_packets ; i++)
-     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
 -  for (i = 0 ; i < transfer->num_iso_packets ; i++) {
 -    unsigned int length = transfer->iso_packet_desc[i].length;
 -    assert(length <= UINT16_MAX);
 -    tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
 -  }
--
--  /* determine the interface/endpoint to use */
--  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
--    usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
--
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
--  /* determine the properties of this endpoint and the speed of the device */
--  (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
--                                                 &transferType, &maxPacketSize, &interval);
--
--  /* Last but not least we need the bus frame number */
--  kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
-   if (kresult) {
 -  if (kresult != kIOReturnSuccess) {
--    usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
--    free(tpriv->isoc_framelist);
--    tpriv->isoc_framelist = NULL;
--
--    return darwin_to_libusb (kresult);
--  }
--
--  (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
--                                                 &transferType, &maxPacketSize, &interval);
--
--  /* schedule for a frame a little in the future */
--  frame += 4;
--
--  if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
--    frame = cInterface->frames[transfer->endpoint];
--
--  /* submit the request */
--  if (IS_XFERIN(transfer))
--    kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
-                                                              transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
 -                                                             (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
--                                                             itransfer);
--  else
--    kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
-                                                               transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
 -                                                              (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
--                                                              itransfer);
--
--  if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
--    /* Full speed */
-     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
 -    cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
--  else
--    /* High/super speed */
-     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
 -    cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
--
--  if (kresult != kIOReturnSuccess) {
--    usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
--               darwin_error_str(kresult));
--    free (tpriv->isoc_framelist);
--    tpriv->isoc_framelist = NULL;
--  }
--
--  return darwin_to_libusb (kresult);
--}
--
--static int submit_control_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--  struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
-   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
 -  struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
--
--  IOReturn               kresult;
--
--  memset(&tpriv->req, 0, sizeof(tpriv->req));
--
--  /* IOUSBDeviceInterface expects the request in cpu endianness */
--  tpriv->req.bmRequestType     = setup->bmRequestType;
--  tpriv->req.bRequest          = setup->bRequest;
--  /* these values should be in bus order from libusb_fill_control_setup */
--  tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
--  tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
--  tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
--  /* data is stored after the libusb control block */
--  tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
--  tpriv->req.completionTimeout = transfer->timeout;
--  tpriv->req.noDataTimeout     = transfer->timeout;
--
--  itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
--
--  /* all transfers in libusb-1.0 are async */
--
--  if (transfer->endpoint) {
--    struct darwin_interface *cInterface;
--    uint8_t                 pipeRef;
--
--    if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
--      usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
--
--      return LIBUSB_ERROR_NOT_FOUND;
--    }
--
--    kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
--  } else
--    /* control request on endpoint 0 */
--    kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
--
--  if (kresult != kIOReturnSuccess)
--    usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
--
--  return darwin_to_libusb (kresult);
--}
--
--static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--
--  switch (transfer->type) {
--  case LIBUSB_TRANSFER_TYPE_CONTROL:
--    return submit_control_transfer(itransfer);
--  case LIBUSB_TRANSFER_TYPE_BULK:
--  case LIBUSB_TRANSFER_TYPE_INTERRUPT:
--    return submit_bulk_transfer(itransfer);
--  case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
--    return submit_iso_transfer(itransfer);
--  case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
--#if InterfaceVersion >= 550
--    return submit_stream_transfer(itransfer);
--#else
--    usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
--    return LIBUSB_ERROR_NOT_SUPPORTED;
--#endif
--  default:
--    usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
--    return LIBUSB_ERROR_INVALID_PARAM;
--  }
--}
--
--static int cancel_control_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
--  IOReturn kresult;
--
--  usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
--
--  if (!dpriv->device)
--    return LIBUSB_ERROR_NO_DEVICE;
--
--  kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
--
--  return darwin_to_libusb (kresult);
--}
--
--static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--  struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
--  struct darwin_interface *cInterface;
--  uint8_t pipeRef, iface;
--  IOReturn kresult;
--
--  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
--    usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
--
--    return LIBUSB_ERROR_NOT_FOUND;
--  }
--
--  if (!dpriv->device)
--    return LIBUSB_ERROR_NO_DEVICE;
--
--  usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
--
--  /* abort transactions */
--#if InterfaceVersion >= 550
--  if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
--    (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
--  else
--#endif
--    (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
--
--  usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
--
--  /* newer versions of darwin support clearing additional bits on the device's endpoint */
--  kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
--
--  return darwin_to_libusb (kresult);
--}
--
--static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
--
--  switch (transfer->type) {
--  case LIBUSB_TRANSFER_TYPE_CONTROL:
--    return cancel_control_transfer(itransfer);
--  case LIBUSB_TRANSFER_TYPE_BULK:
--  case LIBUSB_TRANSFER_TYPE_INTERRUPT:
--  case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
--    return darwin_abort_transfers (itransfer);
--  default:
--    usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
--    return LIBUSB_ERROR_INVALID_PARAM;
-   }
- }
- static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
-   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
-   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
-     free (tpriv->isoc_framelist);
-     tpriv->isoc_framelist = NULL;
--  }
--}
--
--static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
--  struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
 -  struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
--
--  usbi_dbg ("an async io operation has completed");
--
--  /* if requested write a zero packet */
--  if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
--    struct darwin_interface *cInterface;
--    uint8_t pipeRef;
--
--    (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
--
--    (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
--  }
--
--  tpriv->result = result;
--  tpriv->size = (UInt32) (uintptr_t) arg0;
--
--  /* signal the core that this transfer is complete */
--  usbi_signal_transfer_completion(itransfer);
--}
--
- static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
 -static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
--  if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
--    result = kIOUSBTransactionTimeout;
--
--  switch (result) {
--  case kIOReturnUnderrun:
--  case kIOReturnSuccess:
--    return LIBUSB_TRANSFER_COMPLETED;
--  case kIOReturnAborted:
--    return LIBUSB_TRANSFER_CANCELLED;
--  case kIOUSBPipeStalled:
--    usbi_dbg ("transfer error: pipe is stalled");
--    return LIBUSB_TRANSFER_STALL;
--  case kIOReturnOverrun:
--    usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
--    return LIBUSB_TRANSFER_OVERFLOW;
--  case kIOUSBTransactionTimeout:
--    usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
--    itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
--    return LIBUSB_TRANSFER_TIMED_OUT;
--  default:
--    usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
--    return LIBUSB_TRANSFER_ERROR;
--  }
--}
--
--static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
--  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
-   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
-   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
-   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
-   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
-   int i;
 -  struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
 -  const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
 -  const char *transfer_types[max_transfer_type + 1] = {"control", "isoc", "bulk", "interrupt", "bulk-stream"};
 -  bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
--
-   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
 -  if (transfer->type > max_transfer_type) {
--    usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
--    return LIBUSB_ERROR_INVALID_PARAM;
--  }
--
-   usbi_dbg ("handling %s completion with kernel status %d",
-              isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
 -  if (NULL == tpriv) {
 -    usbi_err (TRANSFER_CTX(transfer), "malformed request is missing transfer priv");
 -    return LIBUSB_ERROR_INVALID_PARAM;
 -  }
 -
 -  usbi_dbg ("handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
--
--  if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
-     if (isIsoc && tpriv->isoc_framelist) {
 -    if (is_isoc && tpriv->isoc_framelist) {
--      /* copy isochronous results back */
--
-       for (i = 0; i < transfer->num_iso_packets ; i++) {
 -      for (int i = 0; i < transfer->num_iso_packets ; i++) {
--        struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
-         lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
 -        lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
--        lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
--      }
-     } else if (!isIsoc)
 -    } else if (!is_isoc) {
--      itransfer->transferred += tpriv->size;
 -    }
--  }
--
--  /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
--  return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
--}
--
- static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
- #if !OSX_USE_CLOCK_GETTIME
 -#if !defined(HAVE_CLOCK_GETTIME)
 -void usbi_get_monotonic_time(struct timespec *tp) {
--  mach_timespec_t sys_time;
-   clock_serv_t clock_ref;
-   switch (clk_id) {
-   case USBI_CLOCK_REALTIME:
-     /* CLOCK_REALTIME represents time since the epoch */
-     clock_ref = clock_realtime;
-     break;
-   case USBI_CLOCK_MONOTONIC:
-     /* use system boot time as reference for the monotonic clock */
-     clock_ref = clock_monotonic;
-     break;
-   default:
-     return LIBUSB_ERROR_INVALID_PARAM;
-   }
--
-   clock_get_time (clock_ref, &sys_time);
 -  /* use system boot time as reference for the monotonic clock */
 -  clock_get_time (clock_monotonic, &sys_time);
--
--  tp->tv_sec  = sys_time.tv_sec;
--  tp->tv_nsec = sys_time.tv_nsec;
 -}
--
-   return 0;
- #else
-   switch (clk_id) {
-   case USBI_CLOCK_MONOTONIC:
-     return clock_gettime(CLOCK_MONOTONIC, tp);
-   case USBI_CLOCK_REALTIME:
-     return clock_gettime(CLOCK_REALTIME, tp);
-   default:
-     return LIBUSB_ERROR_INVALID_PARAM;
-   }
- #endif
 -void usbi_get_real_time(struct timespec *tp) {
 -  mach_timespec_t sys_time;
 -
 -  /* CLOCK_REALTIME represents time since the epoch */
 -  clock_get_time (clock_realtime, &sys_time);
 -
 -  tp->tv_sec  = sys_time.tv_sec;
 -  tp->tv_nsec = sys_time.tv_nsec;
--}
 -#endif
--
--#if InterfaceVersion >= 550
--static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
--                                 int num_endpoints) {
--  struct darwin_interface *cInterface;
--  UInt32 supportsStreams;
--  uint8_t pipeRef;
--  int rc, i;
--
-   /* find the mimimum number of supported streams on the endpoint list */
 -  /* find the minimum number of supported streams on the endpoint list */
--  for (i = 0 ; i < num_endpoints ; ++i) {
--    if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
--      return rc;
--    }
--
--    (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
--    if (num_streams > supportsStreams)
--      num_streams = supportsStreams;
--  }
--
--  /* it is an error if any endpoint in endpoints does not support streams */
--  if (0 == num_streams)
--    return LIBUSB_ERROR_INVALID_PARAM;
--
--  /* create the streams */
--  for (i = 0 ; i < num_endpoints ; ++i) {
--    (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
--
--    rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
--    if (kIOReturnSuccess != rc)
--      return darwin_to_libusb(rc);
--  }
--
-   return num_streams;
 -  assert(num_streams <= INT_MAX);
 -  return (int)num_streams;
--}
--
--static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
--  struct darwin_interface *cInterface;
--  UInt32 supportsStreams;
--  uint8_t pipeRef;
--  int rc;
--
--  for (int i = 0 ; i < num_endpoints ; ++i) {
--    if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
--      return rc;
--
--    (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
--    if (0 == supportsStreams)
--      return LIBUSB_ERROR_INVALID_PARAM;
--
--    rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
--    if (kIOReturnSuccess != rc)
--      return darwin_to_libusb(rc);
--  }
--
--  return LIBUSB_SUCCESS;
--}
--#endif
--
--const struct usbi_os_backend usbi_backend = {
--        .name = "Darwin",
--        .caps = 0,
--        .init = darwin_init,
--        .exit = darwin_exit,
-         .get_device_list = NULL, /* not needed */
-         .get_device_descriptor = darwin_get_device_descriptor,
--        .get_active_config_descriptor = darwin_get_active_config_descriptor,
--        .get_config_descriptor = darwin_get_config_descriptor,
--        .hotplug_poll = darwin_hotplug_poll,
--
--        .open = darwin_open,
--        .close = darwin_close,
--        .get_configuration = darwin_get_configuration,
--        .set_configuration = darwin_set_configuration,
--        .claim_interface = darwin_claim_interface,
--        .release_interface = darwin_release_interface,
--
--        .set_interface_altsetting = darwin_set_interface_altsetting,
--        .clear_halt = darwin_clear_halt,
--        .reset_device = darwin_reset_device,
--
--#if InterfaceVersion >= 550
--        .alloc_streams = darwin_alloc_streams,
--        .free_streams = darwin_free_streams,
--#endif
--
--        .kernel_driver_active = darwin_kernel_driver_active,
-         .detach_kernel_driver = darwin_detach_kernel_driver,
-         .attach_kernel_driver = darwin_attach_kernel_driver,
--
--        .destroy_device = darwin_destroy_device,
--
--        .submit_transfer = darwin_submit_transfer,
--        .cancel_transfer = darwin_cancel_transfer,
-         .clear_transfer_priv = darwin_clear_transfer_priv,
--
--        .handle_transfer_completion = darwin_handle_transfer_completion,
-         .clock_gettime = darwin_clock_gettime,
--
--        .device_priv_size = sizeof(struct darwin_device_priv),
--        .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
--        .transfer_priv_size = sizeof(struct darwin_transfer_priv),
--};
diff --cc mac/libusb/os/darwin_usb.h
index 474567f6ac774e80c6931c55353aa2edda2830d8,b799bfd4429e593fadb95b3e0704ea197a9b3177..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,199 -1,203 +1,0 @@@
--/*
-- * darwin backend for libusb 1.0
-  * Copyright © 2008-2015 Nathan Hjelm <hjelmn@users.sourceforge.net>
 - * Copyright © 2008-2019 Nathan Hjelm <hjelmn@users.sourceforge.net>
 - * Copyright © 2019      Google LLC. All rights reserved.
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
--#if !defined(LIBUSB_DARWIN_H)
--#define LIBUSB_DARWIN_H
 -
 -#include <stdbool.h>
--
--#include "libusbi.h"
--
--#include <IOKit/IOTypes.h>
--#include <IOKit/IOCFBundle.h>
--#include <IOKit/usb/IOUSBLib.h>
--#include <IOKit/IOCFPlugIn.h>
--
--/* IOUSBInterfaceInferface */
--
--/* New in OS 10.12.0. */
--#if defined (kIOUSBInterfaceInterfaceID800) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 101200)
--
--#define usb_interface_t IOUSBInterfaceInterface800
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID800
--#define InterfaceVersion 800
--
--/* New in OS 10.10.0. */
--#elif defined (kIOUSBInterfaceInterfaceID700) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 101000)
--
--#define usb_interface_t IOUSBInterfaceInterface700
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID700
--#define InterfaceVersion 700
--
--/* New in OS 10.9.0. */
--#elif defined (kIOUSBInterfaceInterfaceID650) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1090)
--
--#define usb_interface_t IOUSBInterfaceInterface650
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID650
--#define InterfaceVersion 650
--
--/* New in OS 10.8.2 but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBInterfaceInterfaceID550) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1090)
--
--#define usb_interface_t IOUSBInterfaceInterface550
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID550
--#define InterfaceVersion 550
--
--/* New in OS 10.7.3 but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBInterfaceInterfaceID500) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
--
--#define usb_interface_t IOUSBInterfaceInterface500
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID500
--#define InterfaceVersion 500
--
--/* New in OS 10.5.0. */
--#elif defined (kIOUSBInterfaceInterfaceID300) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
--
--#define usb_interface_t IOUSBInterfaceInterface300
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID300
--#define InterfaceVersion 300
--
--/* New in OS 10.4.5 (or 10.4.6?) but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBInterfaceInterfaceID245) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
--
--#define usb_interface_t IOUSBInterfaceInterface245
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID245
--#define InterfaceVersion 245
--
--/* New in OS 10.4.0. */
--#elif defined (kIOUSBInterfaceInterfaceID220) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1040)
--
--#define usb_interface_t IOUSBInterfaceInterface220
--#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID220
--#define InterfaceVersion 220
--
--#else
--
--#error "IOUSBFamily is too old. Please upgrade your SDK and/or deployment target"
--
--#endif
--
--/* IOUSBDeviceInterface */
--
--/* New in OS 10.9.0. */
--#if defined (kIOUSBDeviceInterfaceID650) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1090)
--
--#define usb_device_t    IOUSBDeviceInterface650
--#define DeviceInterfaceID kIOUSBDeviceInterfaceID650
--#define DeviceVersion 650
--
--/* New in OS 10.7.3 but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBDeviceInterfaceID500) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
--
--#define usb_device_t    IOUSBDeviceInterface500
--#define DeviceInterfaceID kIOUSBDeviceInterfaceID500
--#define DeviceVersion 500
--
--/* New in OS 10.5.4 but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBDeviceInterfaceID320) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1060)
--
--#define usb_device_t    IOUSBDeviceInterface320
--#define DeviceInterfaceID kIOUSBDeviceInterfaceID320
--#define DeviceVersion 320
--
--/* New in OS 10.5.0. */
--#elif defined (kIOUSBDeviceInterfaceID300) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
--
--#define usb_device_t    IOUSBDeviceInterface300
--#define DeviceInterfaceID kIOUSBDeviceInterfaceID300
--#define DeviceVersion 300
--
--/* New in OS 10.4.5 (or 10.4.6?) but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBDeviceInterfaceID245) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
--
--#define usb_device_t    IOUSBDeviceInterface245
--#define DeviceInterfaceID kIOUSBDeviceInterfaceID245
--#define DeviceVersion 245
--
--/* New in OS 10.2.3 but can't test deployment target to that granularity, so round up. */
--#elif defined (kIOUSBDeviceInterfaceID197) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1030)
--
--#define usb_device_t    IOUSBDeviceInterface197
--#define DeviceInterfaceID kIOUSBDeviceInterfaceID197
--#define DeviceVersion 197
--
--#else
--
--#error "IOUSBFamily is too old. Please upgrade your SDK and/or deployment target"
--
--#endif
--
--#if !defined(IO_OBJECT_NULL)
--#define IO_OBJECT_NULL ((io_object_t) 0)
--#endif
--
--typedef IOCFPlugInInterface *io_cf_plugin_ref_t;
--typedef IONotificationPortRef io_notification_port_t;
--
--/* private structures */
--struct darwin_cached_device {
--  struct list_head      list;
--  IOUSBDeviceDescriptor dev_descriptor;
--  UInt32                location;
--  UInt64                parent_session;
--  UInt64                session;
-   UInt16                address;
 -  USBDeviceAddress      address;
--  char                  sys_path[21];
--  usb_device_t        **device;
--  int                   open_count;
-   UInt8                 first_config, active_config, port;  
 -  UInt8                 first_config, active_config, port;
--  int                   can_enumerate;
--  int                   refcount;
 -  bool                  in_reenumerate;
--};
--
--struct darwin_device_priv {
--  struct darwin_cached_device *dev;
--};
--
--struct darwin_device_handle_priv {
-   int                  is_open;
 -  bool                 is_open;
--  CFRunLoopSourceRef   cfSource;
--
--  struct darwin_interface {
--    usb_interface_t    **interface;
--    uint8_t              num_endpoints;
--    CFRunLoopSourceRef   cfSource;
--    uint64_t             frames[256];
--    uint8_t              endpoint_addrs[USB_MAXENDPOINTS];
--  } interfaces[USB_MAXINTERFACES];
--};
--
--struct darwin_transfer_priv {
--  /* Isoc */
--  IOUSBIsocFrame *isoc_framelist;
--  int num_iso_packets;
--
--  /* Control */
--  IOUSBDevRequestTO req;
--
--  /* Bulk */
--
--  /* Completion status */
--  IOReturn result;
--  UInt32 size;
--};
--
--#endif
diff --cc mac/libusb/os/threads_posix.c
index 16a7578b81ff001203475de79f603a42cd2ae2be,0e0e22134ebfcf6844cdb3006ab0545b35ef7b5f..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,80 -1,129 +1,0 @@@
--/*
-- * libusb synchronization using POSIX Threads
-- *
-- * Copyright © 2011 Vitali Lovich <vlovich@aliph.com>
-- * Copyright © 2011 Peter Stuge <peter@stuge.se>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
- #include <config.h>
 -#include "libusbi.h"
--
- #include <time.h>
- #if defined(__linux__) || defined(__OpenBSD__)
- # if defined(__OpenBSD__)
- #  define _BSD_SOURCE
- # endif
 -#include <errno.h>
 -#if defined(__ANDROID__)
--# include <unistd.h>
 -#elif defined(__HAIKU__)
 -# include <os/kernel/OS.h>
 -#elif defined(__linux__)
--# include <sys/syscall.h>
- #elif defined(__APPLE__)
- # include <pthread.h>
- #elif defined(__CYGWIN__)
- # include <windows.h>
 -# include <unistd.h>
 -#elif defined(__NetBSD__)
 -# include <lwp.h>
 -#elif defined(__OpenBSD__)
 -# define _BSD_SOURCE
 -# include <sys/syscall.h>
 -# include <unistd.h>
 -#elif defined(__sun__)
 -# include <sys/lwp.h>
--#endif
--
- #include "threads_posix.h"
- #include "libusbi.h"
 -void usbi_cond_init(pthread_cond_t *cond)
 -{
 -#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
 -      pthread_condattr_t condattr;
 -
 -      PTHREAD_CHECK(pthread_condattr_init(&condattr));
 -      PTHREAD_CHECK(pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC));
 -      PTHREAD_CHECK(pthread_cond_init(cond, &condattr));
 -      PTHREAD_CHECK(pthread_condattr_destroy(&condattr));
 -#else
 -      PTHREAD_CHECK(pthread_cond_init(cond, NULL));
 -#endif
 -}
--
--int usbi_cond_timedwait(pthread_cond_t *cond,
--      pthread_mutex_t *mutex, const struct timeval *tv)
--{
--      struct timespec timeout;
--      int r;
--
-       r = usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &timeout);
-       if (r < 0)
-               return r;
 -#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
 -      usbi_get_monotonic_time(&timeout);
 -#else
 -      usbi_get_real_time(&timeout);
 -#endif
--
--      timeout.tv_sec += tv->tv_sec;
-       timeout.tv_nsec += tv->tv_usec * 1000;
-       while (timeout.tv_nsec >= 1000000000L) {
-               timeout.tv_nsec -= 1000000000L;
 -      timeout.tv_nsec += tv->tv_usec * 1000L;
 -      if (timeout.tv_nsec >= NSEC_PER_SEC) {
 -              timeout.tv_nsec -= NSEC_PER_SEC;
--              timeout.tv_sec++;
--      }
--
-       return pthread_cond_timedwait(cond, mutex, &timeout);
 -      r = pthread_cond_timedwait(cond, mutex, &timeout);
 -      if (r == 0)
 -              return 0;
 -      else if (r == ETIMEDOUT)
 -              return LIBUSB_ERROR_TIMEOUT;
 -      else
 -              return LIBUSB_ERROR_OTHER;
--}
--
- int usbi_get_tid(void)
 -unsigned int usbi_get_tid(void)
--{
-       int ret;
 -      static _Thread_local unsigned int tl_tid;
 -      int tid;
 -
 -      if (tl_tid)
 -              return tl_tid;
 -
--#if defined(__ANDROID__)
-       ret = gettid();
 -      tid = gettid();
 -#elif defined(__APPLE__)
 -#ifdef HAVE_PTHREAD_THREADID_NP
 -      uint64_t thread_id;
 -
 -      if (pthread_threadid_np(NULL, &thread_id) == 0)
 -              tid = (int)thread_id;
 -      else
 -              tid = -1;
 -#else
 -      tid = (int)pthread_mach_thread_np(pthread_self());
 -#endif
 -#elif defined(__HAIKU__)
 -      tid = get_pthread_thread_id(pthread_self());
--#elif defined(__linux__)
-       ret = syscall(SYS_gettid);
 -      tid = (int)syscall(SYS_gettid);
 -#elif defined(__NetBSD__)
 -      tid = _lwp_self();
--#elif defined(__OpenBSD__)
--      /* The following only works with OpenBSD > 5.1 as it requires
-          real thread support. For 5.1 and earlier, -1 is returned. */
-       ret = syscall(SYS_getthrid);
- #elif defined(__APPLE__)
-       ret = (int)pthread_mach_thread_np(pthread_self());
- #elif defined(__CYGWIN__)
-       ret = GetCurrentThreadId();
 -       * real thread support. For 5.1 and earlier, -1 is returned. */
 -      tid = syscall(SYS_getthrid);
 -#elif defined(__sun__)
 -      tid = _lwp_self();
--#else
-       ret = -1;
 -      tid = -1;
--#endif
- /* TODO: NetBSD thread ID support */
-       return ret;
 -
 -      if (tid == -1) {
 -              /* If we don't have a thread ID, at least return a unique
 -               * value that can be used to distinguish individual
 -               * threads. */
 -              tid = (int)(intptr_t)pthread_self();
 -      }
 -
 -      return tl_tid = (unsigned int)tid;
--}
diff --cc mac/libusb/os/threads_posix.h
index 9f1ef94bc7a87aa2266b09faa3034181631d4de3,932283402e36b4d6d36d231808aaf76d87c19ed0..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,102 -1,98 +1,0 @@@
--/*
-- * libusb synchronization using POSIX Threads
-- *
-- * Copyright © 2010 Peter Stuge <peter@stuge.se>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
--#ifndef LIBUSB_THREADS_POSIX_H
--#define LIBUSB_THREADS_POSIX_H
--
--#include <pthread.h>
- #ifdef HAVE_SYS_TIME_H
- #include <sys/time.h>
- #endif
 -
 -#define PTHREAD_CHECK(expression)     ASSERT_EQ(expression, 0)
--
--#define USBI_MUTEX_INITIALIZER        PTHREAD_MUTEX_INITIALIZER
--typedef pthread_mutex_t usbi_mutex_static_t;
--static inline void usbi_mutex_static_lock(usbi_mutex_static_t *mutex)
--{
-       (void)pthread_mutex_lock(mutex);
 -      PTHREAD_CHECK(pthread_mutex_lock(mutex));
--}
--static inline void usbi_mutex_static_unlock(usbi_mutex_static_t *mutex)
--{
-       (void)pthread_mutex_unlock(mutex);
 -      PTHREAD_CHECK(pthread_mutex_unlock(mutex));
--}
--
--typedef pthread_mutex_t usbi_mutex_t;
- static inline int usbi_mutex_init(usbi_mutex_t *mutex)
 -static inline void usbi_mutex_init(usbi_mutex_t *mutex)
--{
-       return pthread_mutex_init(mutex, NULL);
 -      PTHREAD_CHECK(pthread_mutex_init(mutex, NULL));
--}
--static inline void usbi_mutex_lock(usbi_mutex_t *mutex)
--{
-       (void)pthread_mutex_lock(mutex);
 -      PTHREAD_CHECK(pthread_mutex_lock(mutex));
--}
--static inline void usbi_mutex_unlock(usbi_mutex_t *mutex)
--{
-       (void)pthread_mutex_unlock(mutex);
 -      PTHREAD_CHECK(pthread_mutex_unlock(mutex));
--}
--static inline int usbi_mutex_trylock(usbi_mutex_t *mutex)
--{
-       return pthread_mutex_trylock(mutex);
 -      return pthread_mutex_trylock(mutex) == 0;
--}
--static inline void usbi_mutex_destroy(usbi_mutex_t *mutex)
--{
-       (void)pthread_mutex_destroy(mutex);
 -      PTHREAD_CHECK(pthread_mutex_destroy(mutex));
--}
--
--typedef pthread_cond_t usbi_cond_t;
- static inline void usbi_cond_init(pthread_cond_t *cond)
- {
-       (void)pthread_cond_init(cond, NULL);
- }
- static inline int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex)
 -void usbi_cond_init(pthread_cond_t *cond);
 -static inline void usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex)
--{
-       return pthread_cond_wait(cond, mutex);
 -      PTHREAD_CHECK(pthread_cond_wait(cond, mutex));
--}
--int usbi_cond_timedwait(usbi_cond_t *cond,
--      usbi_mutex_t *mutex, const struct timeval *tv);
--static inline void usbi_cond_broadcast(usbi_cond_t *cond)
--{
-       (void)pthread_cond_broadcast(cond);
 -      PTHREAD_CHECK(pthread_cond_broadcast(cond));
--}
--static inline void usbi_cond_destroy(usbi_cond_t *cond)
--{
-       (void)pthread_cond_destroy(cond);
 -      PTHREAD_CHECK(pthread_cond_destroy(cond));
--}
--
--typedef pthread_key_t usbi_tls_key_t;
--static inline void usbi_tls_key_create(usbi_tls_key_t *key)
--{
-       (void)pthread_key_create(key, NULL);
 -      PTHREAD_CHECK(pthread_key_create(key, NULL));
--}
--static inline void *usbi_tls_key_get(usbi_tls_key_t key)
--{
--      return pthread_getspecific(key);
--}
--static inline void usbi_tls_key_set(usbi_tls_key_t key, void *ptr)
--{
-       (void)pthread_setspecific(key, ptr);
 -      PTHREAD_CHECK(pthread_setspecific(key, ptr));
--}
--static inline void usbi_tls_key_delete(usbi_tls_key_t key)
--{
-       (void)pthread_key_delete(key);
 -      PTHREAD_CHECK(pthread_key_delete(key));
--}
--
- int usbi_get_tid(void);
 -unsigned int usbi_get_tid(void);
--
--#endif /* LIBUSB_THREADS_POSIX_H */
diff --cc mac/libusb/strerror.c
index d2be0e2a0088af6b71b0663621ee1d80292442c3,9445fa9e87ec2cf50084626cda7c0f2fe59bae5a..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,202 -1,223 +1,0 @@@
--/*
-- * libusb strerror code
-- * Copyright © 2013 Hans de Goede <hdegoede@redhat.com>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
- #include <config.h>
- #include <locale.h>
- #include <stdlib.h>
- #include <string.h>
- #if defined(HAVE_STRINGS_H)
- #include <strings.h>
- #endif
--
--#include "libusbi.h"
- #if defined(_MSC_VER)
- #define strncasecmp _strnicmp
- #endif
--
- static size_t usbi_locale = 0;
 -#include <ctype.h>
 -#include <string.h>
--
--/** \ingroup libusb_misc
-- * How to add a new \ref libusb_strerror() translation:
-- * <ol>
-- * <li> Download the latest \c strerror.c from:<br>
-  *      https://raw.github.com/libusb/libusb/master/libusb/sterror.c </li>
 - *      https://raw.github.com/libusb/libusb/master/libusb/strerror.c </li>
-- * <li> Open the file in an UTF-8 capable editor </li>
-- * <li> Add the 2 letter <a href="http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">ISO 639-1</a>
-- *      code for your locale at the end of \c usbi_locale_supported[]<br>
-- *    Eg. for Chinese, you would add "zh" so that:
-- *    \code... usbi_locale_supported[] = { "en", "nl", "fr" };\endcode
-- *    becomes:
-- *    \code... usbi_locale_supported[] = { "en", "nl", "fr", "zh" };\endcode </li>
-- * <li> Copy the <tt>{ / * English (en) * / ... }</tt> section and add it at the end of \c usbi_localized_errors<br>
-- *    Eg. for Chinese, the last section of \c usbi_localized_errors could look like:
-- *    \code
-- *     }, { / * Chinese (zh) * /
-- *         "Success",
-- *         ...
-- *         "Other error",
-  *     }
 - *     },
-- * };\endcode </li>
-- * <li> Translate each of the English messages from the section you copied into your language </li>
-- * <li> Save the file (in UTF-8 format) and send it to \c libusb-devel\@lists.sourceforge.net </li>
-- * </ol>
-- */
--
- static const char* usbi_locale_supported[] = { "en", "nl", "fr", "ru" };
- static const char* usbi_localized_errors[ARRAYSIZE(usbi_locale_supported)][LIBUSB_ERROR_COUNT] = {
 -static const char * const usbi_locale_supported[] = { "en", "nl", "fr", "ru", "de", "hu" };
 -static const char * const usbi_localized_errors[ARRAYSIZE(usbi_locale_supported)][LIBUSB_ERROR_COUNT] = {
--      { /* English (en) */
--              "Success",
--              "Input/Output Error",
--              "Invalid parameter",
--              "Access denied (insufficient permissions)",
--              "No such device (it may have been disconnected)",
--              "Entity not found",
--              "Resource busy",
--              "Operation timed out",
--              "Overflow",
--              "Pipe error",
--              "System call interrupted (perhaps due to signal)",
--              "Insufficient memory",
--              "Operation not supported or unimplemented on this platform",
--              "Other error",
--      }, { /* Dutch (nl) */
--              "Gelukt",
--              "Invoer-/uitvoerfout",
--              "Ongeldig argument",
--              "Toegang geweigerd (onvoldoende toegangsrechten)",
--              "Apparaat bestaat niet (verbinding met apparaat verbroken?)",
--              "Niet gevonden",
--              "Apparaat of hulpbron is bezig",
--              "Bewerking verlopen",
--              "Waarde is te groot",
--              "Gebroken pijp",
--              "Onderbroken systeemaanroep",
--              "Onvoldoende geheugen beschikbaar",
--              "Bewerking wordt niet ondersteund",
--              "Andere fout",
--      }, { /* French (fr) */
--              "Succès",
--              "Erreur d'entrée/sortie",
--              "Paramètre invalide",
--              "Accès refusé (permissions insuffisantes)",
--              "Périphérique introuvable (peut-être déconnecté)",
--              "Elément introuvable",
--              "Resource déjà occupée",
--              "Operation expirée",
--              "Débordement",
--              "Erreur de pipe",
--              "Appel système abandonné (peut-être à cause d’un signal)",
--              "Mémoire insuffisante",
--              "Opération non supportée or non implémentée sur cette plateforme",
--              "Autre erreur",
--      }, { /* Russian (ru) */
--              "Успех",
--              "Ошибка ввода/вывода",
--              "Неверный параметр",
--              "Доступ запрещён (не хватает прав)",
--              "Устройство отсутствует (возможно, оно было отсоединено)",
--              "Элемент не найден",
--              "Ресурс занят",
--              "Истекло время ожидания операции",
--              "Переполнение",
--              "Ошибка канала",
--              "Системный вызов прерван (возможно, сигналом)",
--              "Память исчерпана",
--              "Операция не поддерживается данной платформой",
--              "Неизвестная ошибка"
-       }
 -      }, { /* German (de) */
 -              "Erfolgreich",
 -              "Eingabe-/Ausgabefehler",
 -              "Ungültiger Parameter",
 -              "Keine Berechtigung (Zugriffsrechte fehlen)",
 -              "Kein passendes Gerät gefunden (es könnte entfernt worden sein)",
 -              "Entität nicht gefunden",
 -              "Die Ressource ist belegt",
 -              "Die Wartezeit für die Operation ist abgelaufen",
 -              "Mehr Daten empfangen als erwartet",
 -              "Datenübergabe unterbrochen (broken pipe)",
 -              "Unterbrechung während des Betriebssystemaufrufs",
 -              "Nicht genügend Hauptspeicher verfügbar",
 -              "Die Operation wird nicht unterstützt oder ist auf dieser Platform nicht implementiert",
 -              "Allgemeiner Fehler",
 -      }, { /* Hungarian (hu) */
 -              "Sikeres",
 -              "Be-/kimeneti hiba",
 -              "Érvénytelen paraméter",
 -              "Hozzáférés megtagadva",
 -              "Az eszköz nem található (eltávolították?)",
 -              "Nem található",
 -              "Az erőforrás foglalt",
 -              "Időtúllépés",
 -              "Túlcsordulás",
 -              "Törött adatcsatorna",
 -              "Rendszerhívás megszakítva",
 -              "Nincs elég memória",
 -              "A művelet nem támogatott ezen a rendszeren",
 -              "Általános hiba",
 -      },
--};
 -
 -static const char * const (*usbi_error_strings)[LIBUSB_ERROR_COUNT] = &usbi_localized_errors[0];
--
--/** \ingroup libusb_misc
-- * Set the language, and only the language, not the encoding! used for
-- * translatable libusb messages.
-- *
-- * This takes a locale string in the default setlocale format: lang[-region]
-- * or lang[_country_region][.codeset]. Only the lang part of the string is
-- * used, and only 2 letter ISO 639-1 codes are accepted for it, such as "de".
-- * The optional region, country_region or codeset parts are ignored. This
-- * means that functions which return translatable strings will NOT honor the
-  * specified encoding. 
 - * specified encoding.
-- * All strings returned are encoded as UTF-8 strings.
-- *
-- * If libusb_setlocale() is not called, all messages will be in English.
-- *
-- * The following functions return translatable strings: libusb_strerror().
-- * Note that the libusb log messages controlled through libusb_set_debug()
-- * are not translated, they are always in English.
-- *
-- * For POSIX UTF-8 environments if you want libusb to follow the standard
-- * locale settings, call libusb_setlocale(setlocale(LC_MESSAGES, NULL)),
-- * after your app has done its locale setup.
-- *
-- * \param locale locale-string in the form of lang[_country_region][.codeset]
-- * or lang[-region], where lang is a 2 letter ISO 639-1 code
-- * \returns LIBUSB_SUCCESS on success
-- * \returns LIBUSB_ERROR_INVALID_PARAM if the locale doesn't meet the requirements
-- * \returns LIBUSB_ERROR_NOT_FOUND if the requested language is not supported
-- * \returns a LIBUSB_ERROR code on other errors
-- */
--
--int API_EXPORTED libusb_setlocale(const char *locale)
--{
--      size_t i;
--
-       if ( (locale == NULL) || (strlen(locale) < 2)
-         || ((strlen(locale) > 2) && (locale[2] != '-') && (locale[2] != '_') && (locale[2] != '.')) )
 -      if (!locale || strlen(locale) < 2
 -          || (locale[2] != '\0' && locale[2] != '-' && locale[2] != '_' && locale[2] != '.'))
--              return LIBUSB_ERROR_INVALID_PARAM;
--
-       for (i=0; i<ARRAYSIZE(usbi_locale_supported); i++) {
-               if (strncasecmp(usbi_locale_supported[i], locale, 2) == 0)
 -      for (i = 0; i < ARRAYSIZE(usbi_locale_supported); i++) {
 -              if (usbi_locale_supported[i][0] == tolower((unsigned char)locale[0])
 -                  && usbi_locale_supported[i][1] == tolower((unsigned char)locale[1]))
--                      break;
--      }
-       if (i >= ARRAYSIZE(usbi_locale_supported)) {
 -
 -      if (i == ARRAYSIZE(usbi_locale_supported))
--              return LIBUSB_ERROR_NOT_FOUND;
-       }
--
-       usbi_locale = i;
 -      usbi_error_strings = &usbi_localized_errors[i];
--
--      return LIBUSB_SUCCESS;
--}
--
--/** \ingroup libusb_misc
-- * Returns a constant string with a short description of the given error code,
-- * this description is intended for displaying to the end user and will be in
-- * the language set by libusb_setlocale().
-- *
-- * The returned string is encoded in UTF-8.
-- *
-- * The messages always start with a capital letter and end without any dot.
-- * The caller must not free() the returned string.
-- *
-- * \param errcode the error code whose description is desired
-- * \returns a short description of the error code in UTF-8 encoding
-- */
- DEFAULT_VISIBILITY const char* LIBUSB_CALL libusb_strerror(enum libusb_error errcode)
 -DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_strerror(int errcode)
--{
--      int errcode_index = -errcode;
--
-       if ((errcode_index < 0) || (errcode_index >= LIBUSB_ERROR_COUNT)) {
 -      if (errcode_index < 0 || errcode_index >= LIBUSB_ERROR_COUNT) {
--              /* "Other Error", which should always be our last message, is returned */
--              errcode_index = LIBUSB_ERROR_COUNT - 1;
--      }
--
-       return usbi_localized_errors[usbi_locale][errcode_index];
 -      return (*usbi_error_strings)[errcode_index];
--}
diff --cc mac/libusb/sync.c
index a609f65f44f41d4b289bf8adcaa3271fae801fae,adc95b4028f3d42218806eb048d36fa7b3c2d26e..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,327 -1,334 +1,0 @@@
 -/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
--/*
-- * Synchronous I/O functions for libusb
-- * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
 - * Copyright © 2019 Nathan Hjelm <hjelmn@cs.unm.edu>
 - * Copyright © 2019 Google LLC. All rights reserved.
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Lesser General Public
-- * License as published by the Free Software Foundation; either
-- * version 2.1 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- * Lesser General Public License for more details.
-- *
-- * You should have received a copy of the GNU Lesser General Public
-- * License along with this library; if not, write to the Free Software
-- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-- */
--
- #include <config.h>
 -#include "libusbi.h"
--
- #include <errno.h>
- #include <stdint.h>
- #include <stdlib.h>
--#include <string.h>
- #include "libusbi.h"
--
--/**
-- * @defgroup libusb_syncio Synchronous device I/O
-- *
-- * This page documents libusb's synchronous (blocking) API for USB device I/O.
-- * This interface is easy to use but has some limitations. More advanced users
-- * may wish to consider using the \ref libusb_asyncio "asynchronous I/O API" instead.
-- */
--
--static void LIBUSB_CALL sync_transfer_cb(struct libusb_transfer *transfer)
--{
--      int *completed = transfer->user_data;
--      *completed = 1;
--      usbi_dbg("actual_length=%d", transfer->actual_length);
--      /* caller interprets result and frees transfer */
--}
--
--static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
--{
--      int r, *completed = transfer->user_data;
--      struct libusb_context *ctx = HANDLE_CTX(transfer->dev_handle);
--
--      while (!*completed) {
--              r = libusb_handle_events_completed(ctx, completed);
--              if (r < 0) {
--                      if (r == LIBUSB_ERROR_INTERRUPTED)
--                              continue;
--                      usbi_err(ctx, "libusb_handle_events failed: %s, cancelling transfer and retrying",
--                               libusb_error_name(r));
--                      libusb_cancel_transfer(transfer);
--                      continue;
 -              }
 -              if (NULL == transfer->dev_handle) {
 -                      /* transfer completion after libusb_close() */
 -                      transfer->status = LIBUSB_TRANSFER_NO_DEVICE;
 -                      *completed = 1;
--              }
--      }
--}
--
--/** \ingroup libusb_syncio
-- * Perform a USB control transfer.
-- *
-- * The direction of the transfer is inferred from the bmRequestType field of
-- * the setup packet.
-- *
-- * The wValue, wIndex and wLength fields values should be given in host-endian
-- * byte order.
-- *
-- * \param dev_handle a handle for the device to communicate with
-- * \param bmRequestType the request type field for the setup packet
-- * \param bRequest the request field for the setup packet
-- * \param wValue the value field for the setup packet
-- * \param wIndex the index field for the setup packet
-- * \param data a suitably-sized data buffer for either input or output
-- * (depending on direction bits within bmRequestType)
-- * \param wLength the length field for the setup packet. The data buffer should
-- * be at least this size.
-  * \param timeout timeout (in millseconds) that this function should wait
 - * \param timeout timeout (in milliseconds) that this function should wait
-- * before giving up due to no response being received. For an unlimited
-- * timeout, use value 0.
-- * \returns on success, the number of bytes actually transferred
-- * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out
-- * \returns LIBUSB_ERROR_PIPE if the control request was not supported by the
-- * device
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_BUSY if called from event handling context
-- * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
-  * the operating system and/or hardware can support
 - * the operating system and/or hardware can support (see \ref asynclimits)
-- * \returns another LIBUSB_ERROR code on other failures
-- */
--int API_EXPORTED libusb_control_transfer(libusb_device_handle *dev_handle,
--      uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
--      unsigned char *data, uint16_t wLength, unsigned int timeout)
--{
--      struct libusb_transfer *transfer;
--      unsigned char *buffer;
--      int completed = 0;
--      int r;
--
--      if (usbi_handling_events(HANDLE_CTX(dev_handle)))
--              return LIBUSB_ERROR_BUSY;
--
--      transfer = libusb_alloc_transfer(0);
--      if (!transfer)
--              return LIBUSB_ERROR_NO_MEM;
--
-       buffer = (unsigned char*) malloc(LIBUSB_CONTROL_SETUP_SIZE + wLength);
 -      buffer = malloc(LIBUSB_CONTROL_SETUP_SIZE + wLength);
--      if (!buffer) {
--              libusb_free_transfer(transfer);
--              return LIBUSB_ERROR_NO_MEM;
--      }
--
--      libusb_fill_control_setup(buffer, bmRequestType, bRequest, wValue, wIndex,
--              wLength);
--      if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
--              memcpy(buffer + LIBUSB_CONTROL_SETUP_SIZE, data, wLength);
--
--      libusb_fill_control_transfer(transfer, dev_handle, buffer,
--              sync_transfer_cb, &completed, timeout);
--      transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
--      r = libusb_submit_transfer(transfer);
--      if (r < 0) {
--              libusb_free_transfer(transfer);
--              return r;
--      }
--
--      sync_transfer_wait_for_completion(transfer);
--
--      if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
--              memcpy(data, libusb_control_transfer_get_data(transfer),
--                      transfer->actual_length);
--
--      switch (transfer->status) {
--      case LIBUSB_TRANSFER_COMPLETED:
--              r = transfer->actual_length;
--              break;
--      case LIBUSB_TRANSFER_TIMED_OUT:
--              r = LIBUSB_ERROR_TIMEOUT;
--              break;
--      case LIBUSB_TRANSFER_STALL:
--              r = LIBUSB_ERROR_PIPE;
--              break;
--      case LIBUSB_TRANSFER_NO_DEVICE:
--              r = LIBUSB_ERROR_NO_DEVICE;
--              break;
--      case LIBUSB_TRANSFER_OVERFLOW:
--              r = LIBUSB_ERROR_OVERFLOW;
--              break;
--      case LIBUSB_TRANSFER_ERROR:
--      case LIBUSB_TRANSFER_CANCELLED:
--              r = LIBUSB_ERROR_IO;
--              break;
--      default:
--              usbi_warn(HANDLE_CTX(dev_handle),
--                      "unrecognised status code %d", transfer->status);
--              r = LIBUSB_ERROR_OTHER;
--      }
--
--      libusb_free_transfer(transfer);
--      return r;
--}
--
--static int do_sync_bulk_transfer(struct libusb_device_handle *dev_handle,
--      unsigned char endpoint, unsigned char *buffer, int length,
--      int *transferred, unsigned int timeout, unsigned char type)
--{
--      struct libusb_transfer *transfer;
--      int completed = 0;
--      int r;
--
--      if (usbi_handling_events(HANDLE_CTX(dev_handle)))
--              return LIBUSB_ERROR_BUSY;
--
--      transfer = libusb_alloc_transfer(0);
--      if (!transfer)
--              return LIBUSB_ERROR_NO_MEM;
--
--      libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer, length,
--              sync_transfer_cb, &completed, timeout);
--      transfer->type = type;
--
--      r = libusb_submit_transfer(transfer);
--      if (r < 0) {
--              libusb_free_transfer(transfer);
--              return r;
--      }
--
--      sync_transfer_wait_for_completion(transfer);
--
--      if (transferred)
--              *transferred = transfer->actual_length;
--
--      switch (transfer->status) {
--      case LIBUSB_TRANSFER_COMPLETED:
--              r = 0;
--              break;
--      case LIBUSB_TRANSFER_TIMED_OUT:
--              r = LIBUSB_ERROR_TIMEOUT;
--              break;
--      case LIBUSB_TRANSFER_STALL:
--              r = LIBUSB_ERROR_PIPE;
--              break;
--      case LIBUSB_TRANSFER_OVERFLOW:
--              r = LIBUSB_ERROR_OVERFLOW;
--              break;
--      case LIBUSB_TRANSFER_NO_DEVICE:
--              r = LIBUSB_ERROR_NO_DEVICE;
--              break;
--      case LIBUSB_TRANSFER_ERROR:
--      case LIBUSB_TRANSFER_CANCELLED:
--              r = LIBUSB_ERROR_IO;
--              break;
--      default:
--              usbi_warn(HANDLE_CTX(dev_handle),
--                      "unrecognised status code %d", transfer->status);
--              r = LIBUSB_ERROR_OTHER;
--      }
--
--      libusb_free_transfer(transfer);
--      return r;
--}
--
--/** \ingroup libusb_syncio
-- * Perform a USB bulk transfer. The direction of the transfer is inferred from
-- * the direction bits of the endpoint address.
-- *
-- * For bulk reads, the <tt>length</tt> field indicates the maximum length of
-- * data you are expecting to receive. If less data arrives than expected,
-- * this function will return that data, so be sure to check the
-- * <tt>transferred</tt> output parameter.
-- *
-- * You should also check the <tt>transferred</tt> parameter for bulk writes.
-- * Not all of the data may have been written.
-- *
-- * Also check <tt>transferred</tt> when dealing with a timeout error code.
-- * libusb may have to split your transfer into a number of chunks to satisfy
-- * underlying O/S requirements, meaning that the timeout may expire after
-- * the first few chunks have completed. libusb is careful not to lose any data
-- * that may have been transferred; do not assume that timeout conditions
-  * indicate a complete lack of I/O.
 - * indicate a complete lack of I/O. See \ref asynctimeout for more details.
-- *
-- * \param dev_handle a handle for the device to communicate with
-- * \param endpoint the address of a valid endpoint to communicate with
-- * \param data a suitably-sized data buffer for either input or output
-- * (depending on endpoint)
-- * \param length for bulk writes, the number of bytes from data to be sent. for
-- * bulk reads, the maximum number of bytes to receive into the data buffer.
-- * \param transferred output location for the number of bytes actually
-- * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105),
-- * it is legal to pass a NULL pointer if you do not wish to receive this
-- * information.
-  * \param timeout timeout (in millseconds) that this function should wait
 - * \param timeout timeout (in milliseconds) that this function should wait
-- * before giving up due to no response being received. For an unlimited
-- * timeout, use value 0.
-- *
-- * \returns 0 on success (and populates <tt>transferred</tt>)
-- * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out (and populates
-- * <tt>transferred</tt>)
-- * \returns LIBUSB_ERROR_PIPE if the endpoint halted
-- * \returns LIBUSB_ERROR_OVERFLOW if the device offered more data, see
-- * \ref libusb_packetoverflow
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_BUSY if called from event handling context
 - * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
 - * the operating system and/or hardware can support (see \ref asynclimits)
-- * \returns another LIBUSB_ERROR code on other failures
-- */
- int API_EXPORTED libusb_bulk_transfer(struct libusb_device_handle *dev_handle,
-       unsigned char endpoint, unsigned char *data, int length, int *transferred,
-       unsigned int timeout)
 -int API_EXPORTED libusb_bulk_transfer(libusb_device_handle *dev_handle,
 -      unsigned char endpoint, unsigned char *data, int length,
 -      int *transferred, unsigned int timeout)
--{
--      return do_sync_bulk_transfer(dev_handle, endpoint, data, length,
--              transferred, timeout, LIBUSB_TRANSFER_TYPE_BULK);
--}
--
--/** \ingroup libusb_syncio
-- * Perform a USB interrupt transfer. The direction of the transfer is inferred
-- * from the direction bits of the endpoint address.
-- *
-- * For interrupt reads, the <tt>length</tt> field indicates the maximum length
-- * of data you are expecting to receive. If less data arrives than expected,
-- * this function will return that data, so be sure to check the
-- * <tt>transferred</tt> output parameter.
-- *
-- * You should also check the <tt>transferred</tt> parameter for interrupt
-- * writes. Not all of the data may have been written.
-- *
-- * Also check <tt>transferred</tt> when dealing with a timeout error code.
-- * libusb may have to split your transfer into a number of chunks to satisfy
-- * underlying O/S requirements, meaning that the timeout may expire after
-- * the first few chunks have completed. libusb is careful not to lose any data
-- * that may have been transferred; do not assume that timeout conditions
-  * indicate a complete lack of I/O.
 - * indicate a complete lack of I/O. See \ref asynctimeout for more details.
-- *
-- * The default endpoint bInterval value is used as the polling interval.
-- *
-- * \param dev_handle a handle for the device to communicate with
-- * \param endpoint the address of a valid endpoint to communicate with
-- * \param data a suitably-sized data buffer for either input or output
-- * (depending on endpoint)
-- * \param length for bulk writes, the number of bytes from data to be sent. for
-- * bulk reads, the maximum number of bytes to receive into the data buffer.
-- * \param transferred output location for the number of bytes actually
-- * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105),
-- * it is legal to pass a NULL pointer if you do not wish to receive this
-- * information.
-  * \param timeout timeout (in millseconds) that this function should wait
 - * \param timeout timeout (in milliseconds) that this function should wait
-- * before giving up due to no response being received. For an unlimited
-- * timeout, use value 0.
-- *
-- * \returns 0 on success (and populates <tt>transferred</tt>)
-- * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out
-- * \returns LIBUSB_ERROR_PIPE if the endpoint halted
-- * \returns LIBUSB_ERROR_OVERFLOW if the device offered more data, see
-- * \ref libusb_packetoverflow
-- * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
-- * \returns LIBUSB_ERROR_BUSY if called from event handling context
 - * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
 - * the operating system and/or hardware can support (see \ref asynclimits)
-- * \returns another LIBUSB_ERROR code on other error
-- */
- int API_EXPORTED libusb_interrupt_transfer(
-       struct libusb_device_handle *dev_handle, unsigned char endpoint,
-       unsigned char *data, int length, int *transferred, unsigned int timeout)
 -int API_EXPORTED libusb_interrupt_transfer(libusb_device_handle *dev_handle,
 -      unsigned char endpoint, unsigned char *data, int length,
 -      int *transferred, unsigned int timeout)
--{
--      return do_sync_bulk_transfer(dev_handle, endpoint, data, length,
--              transferred, timeout, LIBUSB_TRANSFER_TYPE_INTERRUPT);
--}
diff --cc mac/libusb/version.h
index c6dfe370934450cb2439a87af191206d32df4e93,d8ebde4e394d6e1b072f673e281361402bb937b9..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,18 -1,18 +1,0 @@@
--/* This file is parsed by m4 and windres and RC.EXE so please keep it simple. */
--#include "version_nano.h"
--#ifndef LIBUSB_MAJOR
--#define LIBUSB_MAJOR 1
--#endif
--#ifndef LIBUSB_MINOR
--#define LIBUSB_MINOR 0
--#endif
--#ifndef LIBUSB_MICRO
- #define LIBUSB_MICRO 22
 -#define LIBUSB_MICRO 24
--#endif
--#ifndef LIBUSB_NANO
--#define LIBUSB_NANO 0
--#endif
--/* LIBUSB_RC is the release candidate suffix. Should normally be empty. */
--#ifndef LIBUSB_RC
--#define LIBUSB_RC ""
--#endif
diff --cc mac/libusb/version_nano.h
index 90a782a6bf943ad3f2c286a5573d63d14b8588e8,0f100a82478c5c09f44f31712680d4a7d6157a8d..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1 -1,1 +1,0 @@@
- #define LIBUSB_NANO 11312
 -#define LIBUSB_NANO 11584
diff --cc shapelib/.gitignore
index 5fc607b9e2fba31acca73ef4137aaf02482a55a1,5fc607b9e2fba31acca73ef4137aaf02482a55a1..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1 -1,1 +1,0 @@@
--/Makefile
diff --cc shapelib/COPYING
index 0b643ac83c8bb328c7ce336531f77c51c3f73fe7,0b643ac83c8bb328c7ce336531f77c51c3f73fe7..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,483 -1,483 +1,0 @@@
--
--                GNU LIBRARY GENERAL PUBLIC LICENSE
--                     Version 2, June 1991
--
-- Copyright (C) 1991 Free Software Foundation, Inc.
--                    675 Mass Ave, Cambridge, MA 02139, USA
-- Everyone is permitted to copy and distribute verbatim copies
-- of this license document, but changing it is not allowed.
--
--[This is the first released version of the library GPL.  It is
-- numbered 2 because it goes with version 2 of the ordinary GPL.]
--
--                          Preamble
--
--  The licenses for most software are designed to take away your
--freedom to share and change it.  By contrast, the GNU General Public
--Licenses are intended to guarantee your freedom to share and change
--free software--to make sure the software is free for all its users.
--
--  This license, the Library General Public License, applies to some
--specially designated Free Software Foundation software, and to any
--other libraries whose authors decide to use it.  You can use it for
--your libraries, too.
--
--  When we speak of free software, we are referring to freedom, not
--price.  Our General Public Licenses are designed to make sure that you
--have the freedom to distribute copies of free software (and charge for
--this service if you wish), that you receive source code or can get it
--if you want it, that you can change the software or use pieces of it
--in new free programs; and that you know you can do these things.
--
--  To protect your rights, we need to make restrictions that forbid
--anyone to deny you these rights or to ask you to surrender the rights.
--These restrictions translate to certain responsibilities for you if
--you distribute copies of the library, or if you modify it.
--
--  For example, if you distribute copies of the library, whether gratis
--or for a fee, you must give the recipients all the rights that we gave
--you.  You must make sure that they, too, receive or can get the source
--code.  If you link a program with the library, you must provide
--complete object files to the recipients so that they can relink them
--with the library, after making changes to the library and recompiling
--it.  And you must show them these terms so they know their rights.
--
--  Our method of protecting your rights has two steps: (1) copyright
--the library, and (2) offer you this license which gives you legal
--permission to copy, distribute and/or modify the library.
--
--  Also, for each distributor's protection, we want to make certain
--that everyone understands that there is no warranty for this free
--library.  If the library is modified by someone else and passed on, we
--want its recipients to know that what they have is not the original
--version, so that any problems introduced by others will not reflect on
--the original authors' reputations.
--\f
--  Finally, any free program is threatened constantly by software
--patents.  We wish to avoid the danger that companies distributing free
--software will individually obtain patent licenses, thus in effect
--transforming the program into proprietary software.  To prevent this,
--we have made it clear that any patent must be licensed for everyone's
--free use or not licensed at all.
--
--  Most GNU software, including some libraries, is covered by the ordinary
--GNU General Public License, which was designed for utility programs.  This
--license, the GNU Library General Public License, applies to certain
--designated libraries.  This license is quite different from the ordinary
--one; be sure to read it in full, and don't assume that anything in it is
--the same as in the ordinary license.
--
--  The reason we have a separate public license for some libraries is that
--they blur the distinction we usually make between modifying or adding to a
--program and simply using it.  Linking a program with a library, without
--changing the library, is in some sense simply using the library, and is
--analogous to running a utility program or application program.  However, in
--a textual and legal sense, the linked executable is a combined work, a
--derivative of the original library, and the ordinary General Public License
--treats it as such.
--
--  Because of this blurred distinction, using the ordinary General
--Public License for libraries did not effectively promote software
--sharing, because most developers did not use the libraries.  We
--concluded that weaker conditions might promote sharing better.
--
--  However, unrestricted linking of non-free programs would deprive the
--users of those programs of all benefit from the free status of the
--libraries themselves.  This Library General Public License is intended to
--permit developers of non-free programs to use free libraries, while
--preserving your freedom as a user of such programs to change the free
--libraries that are incorporated in them.  (We have not seen how to achieve
--this as regards changes in header files, but we have achieved it as regards
--changes in the actual functions of the Library.)  The hope is that this
--will lead to faster development of free libraries.
--
--  The precise terms and conditions for copying, distribution and
--modification follow.  Pay close attention to the difference between a
--"work based on the library" and a "work that uses the library".  The
--former contains code derived from the library, while the latter only
--works together with the library.
--
--  Note that it is possible for a library to be covered by the ordinary
--General Public License rather than by this special one.
--\f
--                GNU LIBRARY GENERAL PUBLIC LICENSE
--   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
--
--  0. This License Agreement applies to any software library which
--contains a notice placed by the copyright holder or other authorized
--party saying it may be distributed under the terms of this Library
--General Public License (also called "this License").  Each licensee is
--addressed as "you".
--
--  A "library" means a collection of software functions and/or data
--prepared so as to be conveniently linked with application programs
--(which use some of those functions and data) to form executables.
--
--  The "Library", below, refers to any such software library or work
--which has been distributed under these terms.  A "work based on the
--Library" means either the Library or any derivative work under
--copyright law: that is to say, a work containing the Library or a
--portion of it, either verbatim or with modifications and/or translated
--straightforwardly into another language.  (Hereinafter, translation is
--included without limitation in the term "modification".)
--
--  "Source code" for a work means the preferred form of the work for
--making modifications to it.  For a library, complete source code means
--all the source code for all modules it contains, plus any associated
--interface definition files, plus the scripts used to control compilation
--and installation of the library.
--
--  Activities other than copying, distribution and modification are not
--covered by this License; they are outside its scope.  The act of
--running a program using the Library is not restricted, and output from
--such a program is covered only if its contents constitute a work based
--on the Library (independent of the use of the Library in a tool for
--writing it).  Whether that is true depends on what the Library does
--and what the program that uses the Library does.
--  
--  1. You may copy and distribute verbatim copies of the Library's
--complete source code as you receive it, in any medium, provided that
--you conspicuously and appropriately publish on each copy an
--appropriate copyright notice and disclaimer of warranty; keep intact
--all the notices that refer to this License and to the absence of any
--warranty; and distribute a copy of this License along with the
--Library.
--
--  You may charge a fee for the physical act of transferring a copy,
--and you may at your option offer warranty protection in exchange for a
--fee.
--\f
--  2. You may modify your copy or copies of the Library or any portion
--of it, thus forming a work based on the Library, and copy and
--distribute such modifications or work under the terms of Section 1
--above, provided that you also meet all of these conditions:
--
--    a) The modified work must itself be a software library.
--
--    b) You must cause the files modified to carry prominent notices
--    stating that you changed the files and the date of any change.
--
--    c) You must cause the whole of the work to be licensed at no
--    charge to all third parties under the terms of this License.
--
--    d) If a facility in the modified Library refers to a function or a
--    table of data to be supplied by an application program that uses
--    the facility, other than as an argument passed when the facility
--    is invoked, then you must make a good faith effort to ensure that,
--    in the event an application does not supply such function or
--    table, the facility still operates, and performs whatever part of
--    its purpose remains meaningful.
--
--    (For example, a function in a library to compute square roots has
--    a purpose that is entirely well-defined independent of the
--    application.  Therefore, Subsection 2d requires that any
--    application-supplied function or table used by this function must
--    be optional: if the application does not supply it, the square
--    root function must still compute square roots.)
--
--These requirements apply to the modified work as a whole.  If
--identifiable sections of that work are not derived from the Library,
--and can be reasonably considered independent and separate works in
--themselves, then this License, and its terms, do not apply to those
--sections when you distribute them as separate works.  But when you
--distribute the same sections as part of a whole which is a work based
--on the Library, the distribution of the whole must be on the terms of
--this License, whose permissions for other licensees extend to the
--entire whole, and thus to each and every part regardless of who wrote
--it.
--
--Thus, it is not the intent of this section to claim rights or contest
--your rights to work written entirely by you; rather, the intent is to
--exercise the right to control the distribution of derivative or
--collective works based on the Library.
--
--In addition, mere aggregation of another work not based on the Library
--with the Library (or with a work based on the Library) on a volume of
--a storage or distribution medium does not bring the other work under
--the scope of this License.
--
--  3. You may opt to apply the terms of the ordinary GNU General Public
--License instead of this License to a given copy of the Library.  To do
--this, you must alter all the notices that refer to this License, so
--that they refer to the ordinary GNU General Public License, version 2,
--instead of to this License.  (If a newer version than version 2 of the
--ordinary GNU General Public License has appeared, then you can specify
--that version instead if you wish.)  Do not make any other change in
--these notices.
--\f
--  Once this change is made in a given copy, it is irreversible for
--that copy, so the ordinary GNU General Public License applies to all
--subsequent copies and derivative works made from that copy.
--
--  This option is useful when you wish to copy part of the code of
--the Library into a program that is not a library.
--
--  4. You may copy and distribute the Library (or a portion or
--derivative of it, under Section 2) in object code or executable form
--under the terms of Sections 1 and 2 above provided that you accompany
--it with the complete corresponding machine-readable source code, which
--must be distributed under the terms of Sections 1 and 2 above on a
--medium customarily used for software interchange.
--
--  If distribution of object code is made by offering access to copy
--from a designated place, then offering equivalent access to copy the
--source code from the same place satisfies the requirement to
--distribute the source code, even though third parties are not
--compelled to copy the source along with the object code.
--
--  5. A program that contains no derivative of any portion of the
--Library, but is designed to work with the Library by being compiled or
--linked with it, is called a "work that uses the Library".  Such a
--work, in isolation, is not a derivative work of the Library, and
--therefore falls outside the scope of this License.
--
--  However, linking a "work that uses the Library" with the Library
--creates an executable that is a derivative of the Library (because it
--contains portions of the Library), rather than a "work that uses the
--library".  The executable is therefore covered by this License.
--Section 6 states terms for distribution of such executables.
--
--  When a "work that uses the Library" uses material from a header file
--that is part of the Library, the object code for the work may be a
--derivative work of the Library even though the source code is not.
--Whether this is true is especially significant if the work can be
--linked without the Library, or if the work is itself a library.  The
--threshold for this to be true is not precisely defined by law.
--
--  If such an object file uses only numerical parameters, data
--structure layouts and accessors, and small macros and small inline
--functions (ten lines or less in length), then the use of the object
--file is unrestricted, regardless of whether it is legally a derivative
--work.  (Executables containing this object code plus portions of the
--Library will still fall under Section 6.)
--
--  Otherwise, if the work is a derivative of the Library, you may
--distribute the object code for the work under the terms of Section 6.
--Any executables containing that work also fall under Section 6,
--whether or not they are linked directly with the Library itself.
--\f
--  6. As an exception to the Sections above, you may also compile or
--link a "work that uses the Library" with the Library to produce a
--work containing portions of the Library, and distribute that work
--under terms of your choice, provided that the terms permit
--modification of the work for the customer's own use and reverse
--engineering for debugging such modifications.
--
--  You must give prominent notice with each copy of the work that the
--Library is used in it and that the Library and its use are covered by
--this License.  You must supply a copy of this License.  If the work
--during execution displays copyright notices, you must include the
--copyright notice for the Library among them, as well as a reference
--directing the user to the copy of this License.  Also, you must do one
--of these things:
--
--    a) Accompany the work with the complete corresponding
--    machine-readable source code for the Library including whatever
--    changes were used in the work (which must be distributed under
--    Sections 1 and 2 above); and, if the work is an executable linked
--    with the Library, with the complete machine-readable "work that
--    uses the Library", as object code and/or source code, so that the
--    user can modify the Library and then relink to produce a modified
--    executable containing the modified Library.  (It is understood
--    that the user who changes the contents of definitions files in the
--    Library will not necessarily be able to recompile the application
--    to use the modified definitions.)
--
--    b) Accompany the work with a written offer, valid for at
--    least three years, to give the same user the materials
--    specified in Subsection 6a, above, for a charge no more
--    than the cost of performing this distribution.
--
--    c) If distribution of the work is made by offering access to copy
--    from a designated place, offer equivalent access to copy the above
--    specified materials from the same place.
--
--    d) Verify that the user has already received a copy of these
--    materials or that you have already sent this user a copy.
--
--  For an executable, the required form of the "work that uses the
--Library" must include any data and utility programs needed for
--reproducing the executable from it.  However, as a special exception,
--the source code distributed need not include anything that is normally
--distributed (in either source or binary form) with the major
--components (compiler, kernel, and so on) of the operating system on
--which the executable runs, unless that component itself accompanies
--the executable.
--
--  It may happen that this requirement contradicts the license
--restrictions of other proprietary libraries that do not normally
--accompany the operating system.  Such a contradiction means you cannot
--use both them and the Library together in an executable that you
--distribute.
--\f
--  7. You may place library facilities that are a work based on the
--Library side-by-side in a single library together with other library
--facilities not covered by this License, and distribute such a combined
--library, provided that the separate distribution of the work based on
--the Library and of the other library facilities is otherwise
--permitted, and provided that you do these two things:
--
--    a) Accompany the combined library with a copy of the same work
--    based on the Library, uncombined with any other library
--    facilities.  This must be distributed under the terms of the
--    Sections above.
--
--    b) Give prominent notice with the combined library of the fact
--    that part of it is a work based on the Library, and explaining
--    where to find the accompanying uncombined form of the same work.
--
--  8. You may not copy, modify, sublicense, link with, or distribute
--the Library except as expressly provided under this License.  Any
--attempt otherwise to copy, modify, sublicense, link with, or
--distribute the Library is void, and will automatically terminate your
--rights under this License.  However, parties who have received copies,
--or rights, from you under this License will not have their licenses
--terminated so long as such parties remain in full compliance.
--
--  9. You are not required to accept this License, since you have not
--signed it.  However, nothing else grants you permission to modify or
--distribute the Library or its derivative works.  These actions are
--prohibited by law if you do not accept this License.  Therefore, by
--modifying or distributing the Library (or any work based on the
--Library), you indicate your acceptance of this License to do so, and
--all its terms and conditions for copying, distributing or modifying
--the Library or works based on it.
--
--  10. Each time you redistribute the Library (or any work based on the
--Library), the recipient automatically receives a license from the
--original licensor to copy, distribute, link with or modify the Library
--subject to these terms and conditions.  You may not impose any further
--restrictions on the recipients' exercise of the rights granted herein.
--You are not responsible for enforcing compliance by third parties to
--this License.
--\f
--  11. If, as a consequence of a court judgment or allegation of patent
--infringement or for any other reason (not limited to patent issues),
--conditions are imposed on you (whether by court order, agreement or
--otherwise) that contradict the conditions of this License, they do not
--excuse you from the conditions of this License.  If you cannot
--distribute so as to satisfy simultaneously your obligations under this
--License and any other pertinent obligations, then as a consequence you
--may not distribute the Library at all.  For example, if a patent
--license would not permit royalty-free redistribution of the Library by
--all those who receive copies directly or indirectly through you, then
--the only way you could satisfy both it and this License would be to
--refrain entirely from distribution of the Library.
--
--If any portion of this section is held invalid or unenforceable under any
--particular circumstance, the balance of the section is intended to apply,
--and the section as a whole is intended to apply in other circumstances.
--
--It is not the purpose of this section to induce you to infringe any
--patents or other property right claims or to contest validity of any
--such claims; this section has the sole purpose of protecting the
--integrity of the free software distribution system which is
--implemented by public license practices.  Many people have made
--generous contributions to the wide range of software distributed
--through that system in reliance on consistent application of that
--system; it is up to the author/donor to decide if he or she is willing
--to distribute software through any other system and a licensee cannot
--impose that choice.
--
--This section is intended to make thoroughly clear what is believed to
--be a consequence of the rest of this License.
--
--  12. If the distribution and/or use of the Library is restricted in
--certain countries either by patents or by copyrighted interfaces, the
--original copyright holder who places the Library under this License may add
--an explicit geographical distribution limitation excluding those countries,
--so that distribution is permitted only in or among countries not thus
--excluded.  In such case, this License incorporates the limitation as if
--written in the body of this License.
--
--  13. The Free Software Foundation may publish revised and/or new
--versions of the Library General Public License from time to time.
--Such new versions will be similar in spirit to the present version,
--but may differ in detail to address new problems or concerns.
--
--Each version is given a distinguishing version number.  If the Library
--specifies a version number of this License which applies to it and
--"any later version", you have the option of following the terms and
--conditions either of that version or of any later version published by
--the Free Software Foundation.  If the Library does not specify a
--license version number, you may choose any version ever published by
--the Free Software Foundation.
--\f
--  14. If you wish to incorporate parts of the Library into other free
--programs whose distribution conditions are incompatible with these,
--write to the author to ask for permission.  For software which is
--copyrighted by the Free Software Foundation, write to the Free
--Software Foundation; we sometimes make exceptions for this.  Our
--decision will be guided by the two goals of preserving the free status
--of all derivatives of our free software and of promoting the sharing
--and reuse of software generally.
--
--                          NO WARRANTY
--
--  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
--WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
--EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
--OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
--KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
--IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
--LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
--THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
--
--  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
--WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
--AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
--FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
--CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
--LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
--RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
--FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
--SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
--DAMAGES.
--
--                   END OF TERMS AND CONDITIONS
--\f
--     Appendix: How to Apply These Terms to Your New Libraries
--
--  If you develop a new library, and you want it to be of the greatest
--possible use to the public, we recommend making it free software that
--everyone can redistribute and change.  You can do so by permitting
--redistribution under these terms (or, alternatively, under the terms of the
--ordinary General Public License).
--
--  To apply these terms, attach the following notices to the library.  It is
--safest to attach them to the start of each source file to most effectively
--convey the exclusion of warranty; and each file should have at least the
--"copyright" line and a pointer to where the full notice is found.
--
--    <one line to give the library's name and a brief idea of what it does.>
--    Copyright (C) <year>  <name of author>
--
--    This library is free software; you can redistribute it and/or
--    modify it under the terms of the GNU Library General Public
--    License as published by the Free Software Foundation; either
--    version 2 of the License, or (at your option) any later version.
--
--    This library is distributed in the hope that it will be useful,
--    but WITHOUT ANY WARRANTY; without even the implied warranty of
--    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--    Library General Public License for more details.
--
--    You should have received a copy of the GNU Library General Public
--    License along with this library; if not, write to the Free
--    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
--
--Also add information on how to contact you by electronic and paper mail.
--
--You should also get your employer (if you work as a programmer) or your
--school, if any, to sign a "copyright disclaimer" for the library, if
--necessary.  Here is a sample; alter the names:
--
--  Yoyodyne, Inc., hereby disclaims all copyright interest in the
--  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
--
--  <signature of Ty Coon>, 1 April 1990
--  Ty Coon, President of Vice
--
--That's all there is to it!
--
diff --cc shapelib/README.GPSBabel
index a3f95350970444612e3f8a70ae0e3b0fc58ed77d,a3f95350970444612e3f8a70ae0e3b0fc58ed77d..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,6 -1,6 +1,0 @@@
--This is a subset of Shapelib v1.5.0 from http://shapelib.maptools.org/
--
--The source is unmodified.  It's subsetted here only to reduce 
--the amount of size in our tree that it takes and to reduce ongoing 
--merge maintenance.
--
diff --cc shapelib/dbf_api.html
index 0bd0da1b84decb32de162adc192a1858949fb5e5,0bd0da1b84decb32de162adc192a1858949fb5e5..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,434 -1,434 +1,0 @@@
--<html>
--<head>
--<title>Attribute (.DBF) API</title>
--</head>
--<body>
--<h1>Attribute (.DBF) API</h1>
--
--The Attribute (DBF) API uses DBFHandle to represent a handle for access
--to one .dbf file.  The contents of the DBFHandle are visible (see shapefil.h)
--but should be ignored by the application.  It is intended that all information
--be accessed by API functions.  Note that there should be exactly one record
--in the .dbf file for each shape in the .shp/.shx files.  This constraint
--must be maintained by the application.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFOpen()</h2>
--
--<pre>
--DBFHandle DBFOpen( const char * pszDBFFile, const char * pszAccess );
--
--  pszDBFFile:         The name of the xBase (.dbf) file to access.
--
--  pszAccess:          The fopen() style access string.  At this time only
--                      "rb" (read-only binary) and "rb+" (read/write binary) 
--                      should be used.
--</pre>
--
--  The DBFOpen() function should be used to establish access to an existing
--  xBase format table file.  The returned DBFHandle is passed to other 
--  access functions, and DBFClose() should be invoked to recover resources, and 
--  flush changes to disk when complete.  The DBFCreate() function should
--  called to create new xBase files.  As a convenience, DBFOpen() can be
--  called with the name of a .shp or .shx file, and it will figure out the
--  name of the related .dbf file.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFCreate()</h2>
--
--<pre>
--DBFHandle DBFCreate( const char * pszDBFFile );
--
--  pszDBFFile:         The name of the xBase (.dbf) file to create.
--</pre>
--  
--  The DBFCreate() function creates a new xBase format file with the given 
--  name, and returns an access handle that can be used with other DBF functions.
--  The newly created file will have no fields, and no records.  Fields should
--  be added with DBFAddField() before any records add written.
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFGetFieldCount()</h2>
--
--<pre>
--int DBFGetFieldCount( DBFHandle hDBF );
--
--  hDBF:               The access handle for the file to be queried, as returned
--                by DBFOpen(), or DBFCreate().
--</pre>
--
--  The DBFGetFieldCount() function returns the number of fields currently
--  defined for the indicated xBase file.
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFGetRecordCount()</h2>
--
--<pre>
--int DBFGetRecordCount( DBFHandle hDBF );
--
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--</pre>
--
--  The DBFGetRecordCount() function returns the number of records that
--  exist on the xBase file currently.  Note that with shape files one xBase
--  record exists for each shape in the .shp/.shx files.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFGetFieldIndex()</h2>
--
--<pre>
--int DBFGetFieldIndex( DBFHandle hDBF, const char *pszFieldName );
--
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--
--  pszFieldName: Name of the field to search for.
--</pre>
--
--  Returns the index of the field matching this name, or -1 on failure.  The
--  comparison is case insensitive.  However, lengths must match exactly.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFGetFieldInfo()</h2>
--
--<pre>
--DBFFieldType DBFGetFieldInfo( DBFHandle hDBF, int iField, char * pszFieldName,
--                              int * pnWidth, int * pnDecimals );
--
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iField:     The field to be queried.  This should be a number between 
--                0 and n-1, where n is the number fields on the file, as
--                returned by DBFGetFieldCount().
--
--  pszFieldName:       If this pointer is not NULL the name of the requested field
--              will be written to this location.  The pszFieldName buffer 
--                should be at least 12 character is size in order to hold
--              the longest possible field name of 11 characters plus a 
--                terminating zero character.
--
--  pnWidth:    If this pointer is not NULL, the width of the requested field
--              will be returned in the int pointed to by pnWidth.  This is
--                the width in characters.  
--
--  pnDecimals: If this pointer is not NULL, the number of decimal places
--                precision defined for the field will be returned.  This is
--                zero for integer fields, or non-numeric fields.
--</pre>
--
--  The DBFGetFieldInfo() returns the type of the requested field, which is
--  one of the DBFFieldType enumerated values.  As well, the field name, and
--  field width information can optionally be returned.  The field type returned
--  does not correspond one to one with the xBase field types.  For instance
--  the xBase field type for Date will just be returned as being FTInteger.  <p>
--
--<pre>
--    typedef enum {
--      FTString,                       /* fixed length string field            */
--      FTInteger,              /* numeric field with no decimals       */
--      FTDouble,                       /* numeric field with decimals          */
--      FTLogical,              /* logical field.                       */
--      FTInvalid                 /* not a recognised field type                */
--    } DBFFieldType;
--</pre>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFAddField()</h2>
--
--<pre>
--int DBFAddField( DBFHandle hDBF, const char * pszFieldName, 
--                 DBFFieldType eType, int nWidth, int nDecimals );
--
--  hDBF:               The access handle for the file to be updated, as returned by
--              DBFOpen(), or DBFCreate().
--
--  pszFieldName:       The name of the new field.  At most 11 character will be used.
--                In order to use the xBase file in some packages it may be
--                necessary to avoid some special characters in the field names
--                such as spaces, or arithmetic operators.
--
--  eType:      One of FTString, FTInteger or FTDouble in order to establish
--                the type of the new field.  Note that some valid xBase field
--                types cannot be created such as date fields.
--
--  nWidth:     The width of the field to be created.  For FTString fields this
--                establishes the maximum length of string that can be stored.
--                For FTInteger this establishes the number of digits of the
--                largest number that can
--                be represented.  For FTDouble fields this in combination
--                with the nDecimals value establish the size, and precision
--                of the created field.
--
--  nDecimals:    The number of decimal places to reserve for FTDouble fields.
--                For all other field types this should be zero.  For instance
--                with nWidth=7, and nDecimals=3 numbers would be formatted
--                similarly to `123.456'.
--</pre>
--
--  The DBFAddField() function is used to add new fields to an existing xBase
--  file opened with DBFOpen(), or created with DBFCreate().<p>
--
--  The DBFAddField() return value is the field number of the new field, or
--  -1 if the addition of the field failed.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFReadIntegerAttribute()</h2>
--
--<pre>
--int DBFReadIntegerAttribute( DBFHandle hDBF, int iShape, int iField );
--  
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) from which the field value
--                should be read.
--
--  iField:     The field within the selected record that should be read.
--</pre>
--
--  The DBFReadIntegerAttribute() will read the value of one field and return
--  it as an integer.  This can be used even with FTString fields, though the
--  returned value will be zero if not interpretable as a number.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFReadDoubleAttribute()</h2>
--
--<pre>
--double DBFReadDoubleAttribute( DBFHandle hDBF, int iShape, int iField );
--  
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) from which the field value
--                should be read.
--
--  iField:     The field within the selected record that should be read.
--</pre>
--
--  The DBFReadDoubleAttribute() will read the value of one field and return
--  it as a double.  This can be used even with FTString fields, though the
--  returned value will be zero if not interpretable as a number.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFReadStringAttribute()</h2>
--
--<pre>
--const char *DBFReadStringAttribute( DBFHandle hDBF, int iShape, int iField );
--  
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) from which the field value
--                should be read.
--
--  iField:     The field within the selected record that should be read.
--</pre>
--
--  The DBFReadStringAttribute() will read the value of one field and return
--  it as a string.  This function may be used on any field type (including 
--  FTInteger and FTDouble) and will return the string representation stored
--  in the .dbf file.  The returned pointer is to an internal buffer
--  which is only valid untill the next DBF function call.  It's contents may
--  be copied with normal string functions such as strcpy(), or strdup().  If
--  the TRIM_DBF_WHITESPACE macro is defined in shapefil.h (it is by default)
--  then all leading and trailing space (ASCII 32) characters will be stripped
--  before the string is returned.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFIsAttributeNULL()</h2>
--
--<pre>
--int DBFIsAttributeNULL( DBFHandle hDBF, int iShape, int iField );
--  
--  hDBF:               The access handle for the file to be queried, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) from which the field value
--                should be read.
--
--  iField:     The field within the selected record that should be read.
--</pre>
--
--  This function will return TRUE if the indicated field is NULL valued
--  otherwise FALSE.  Note that NULL fields are represented in the .dbf file
--  as having all spaces in the field.  Reading NULL fields will result in
--  a value of 0.0 or an empty string with the other DBFRead*Attribute() 
--  functions.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFWriteIntegerAttribute</h2>
--
--<pre>
--int DBFWriteIntegerAttribute( DBFHandle hDBF, int iShape, int iField,
--                              int nFieldValue );
--
--  hDBF:               The access handle for the file to be written, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) to which the field value
--                should be written.
--
--  iField:     The field within the selected record that should be written.
--
--  nFieldValue:        The integer value that should be written.
--</pre>
--
--The DBFWriteIntegerAttribute() function is used to write a value to a numeric
--field (FTInteger, or FTDouble).  If the write succeeds the value TRUE will
--be returned, otherwise FALSE will be returned.  If the value is too large to 
--fit in the field, it will be truncated and FALSE returned.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFWriteDoubleAttribute()</h2>
--
--<pre>
--int DBFWriteDoubleAttribute( DBFHandle hDBF, int iShape, int iField,
--                             double dFieldValue );
--
--  hDBF:               The access handle for the file to be written, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) to which the field value
--                should be written.
--
--  iField:     The field within the selected record that should be written.
--
--  dFieldValue:        The floating point value that should be written.
--</pre>
--
--The DBFWriteDoubleAttribute() function is used to write a value to a numeric
--field (FTInteger, or FTDouble).  If the write succeeds the value TRUE will
--be returned, otherwise FALSE will be returned.  If the value is too large to 
--fit in the field, it will be truncated and FALSE returned.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFWriteStringAttribute()</h2>
--
--<pre>
--int DBFWriteStringAttribute( DBFHandle hDBF, int iShape, int iField,
--                             const char * pszFieldValue );
--
--  hDBF:               The access handle for the file to be written, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) to which the field value
--                should be written.
--
--  iField:     The field within the selected record that should be written.
--
--  pszFieldValue: The string to be written to the field.
--</pre>
--
--The DBFWriteStringAttribute() function is used to write a value to a string
--field (FString).  If the write succeeds the value TRUE willbe returned, 
--otherwise FALSE will be returned.  If the value is too large to 
--fit in the field, it will be truncated and FALSE returned.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFWriteNULLAttribute()</h2>
--
--<pre>
--int DBFWriteNULLAttribute( DBFHandle hDBF, int iShape, int iField );
--
--  hDBF:               The access handle for the file to be written, as returned by
--              DBFOpen(), or DBFCreate().
--
--  iShape:     The record number (shape number) to which the field value
--                should be written.
--
--  iField:     The field within the selected record that should be written.
--</pre>
--
--The DBFWriteNULLAttribute() function is used to clear the indicated field
--to a NULL value.  In the .dbf file this is represented by setting the entire
--field to spaces.  If the write succeeds the value TRUE willbe returned, 
--otherwise FALSE will be returned.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFClose()</h2>
--
--<pre>
--void DBFClose( DBFHandle hDBF );
--
--  hDBF:               The access handle for the file to be closed.
--</pre>
--
--  The DBFClose() function will close the indicated xBase file (opened with
--  DBFOpen(), or DBFCreate()), flushing out all information to the file on
--  disk, and recovering any resources associated with having the file open.
--  The file handle (hDBF) should not be used again with the DBF API after
--  calling DBFClose().<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFIsRecordDeleted()</h2>
--
--<pre>
--int DBFIsRecordDeleted( DBFHandle hDBF, int iShape );
--
--  hDBF:               The access handle for the file to be checked.
--  iShape:       The record index to check.
--</pre>
--
--  Returns TRUE (non-zero) if the record is marked for deletion, otherwise
--  it returns FALSE.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFMarkRecordDeleted()</h2>
--
--<pre>
--int DBFMarkRecordDeleted( DBFHandle hDBF, int iShape, int bIsDeleted );
--
--  hDBF:               The access handle for the file.
--  iShape:       The record index to update.
--  bIsDeleted:   TRUE to mark record deleted, or FALSE to undelete it.
--</pre>
--
--  Returns TRUE on success, or FALSE on error.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>DBFGetNativeFieldType()</h2>
--
--<pre>
--char DBFGetNativeFieldType( DBFHandle hDBF, int iField );
--
--  hDBF:               The access handle for the file.
--  iField:       The field index to query.
--  
--</pre>
--
--  This function returns the DBF type code of the indicated field. It will
--  be one of:<p>
--
--<ul>
--<li> 'C' (String)
--<li> 'D' (Date)
--<li> 'F' (Float)
--<li> 'N' (Numeric, with or without decimal)
--<li> 'L' (Logical)
--<li> 'M' (Memo: 10 digits .DBT block ptr)
--<li> ' ' (field out of range)
--</ul>
--
--</body>
--</html>
diff --cc shapelib/dbfopen.c
index 218db70cf0ee815cfb453c5c9f0607b23635324b,218db70cf0ee815cfb453c5c9f0607b23635324b..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2435 -1,2435 +1,0 @@@
--/******************************************************************************
-- * $Id: dbfopen.c,v 1.94 2018-08-16 15:39:07 erouault Exp $
-- *
-- * Project:  Shapelib
-- * Purpose:  Implementation of .dbf access API documented in dbf_api.html.
-- * Author:   Frank Warmerdam, warmerdam@pobox.com
-- *
-- ******************************************************************************
-- * Copyright (c) 1999, Frank Warmerdam
-- * Copyright (c) 2012-2013, Even Rouault <even dot rouault at mines-paris dot org>
-- *
-- * This software is available under the following "MIT Style" license,
-- * or at the option of the licensee under the LGPL (see COPYING).  This
-- * option is discussed in more detail in shapelib.html.
-- *
-- * --
-- *
-- * Permission is hereby granted, free of charge, to any person obtaining a
-- * copy of this software and associated documentation files (the "Software"),
-- * to deal in the Software without restriction, including without limitation
-- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- * and/or sell copies of the Software, and to permit persons to whom the
-- * Software is furnished to do so, subject to the following conditions:
-- *
-- * The above copyright notice and this permission notice shall be included
-- * in all copies or substantial portions of the Software.
-- *
-- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- * DEALINGS IN THE SOFTWARE.
-- ******************************************************************************
-- *
-- * $Log: dbfopen.c,v $
-- * Revision 1.94  2018-08-16 15:39:07  erouault
-- * * shpopen.c, dbfopen.c, shptree.c, sbnsearch.c: resyc with GDAL
-- * internal shapelib. Mostly to allow building those files as C++
-- * without warning. Also add FTDate entry in DBFFieldType
-- * (see https://github.com/OSGeo/gdal/pull/308). And some other
-- * code cleanups
-- *
-- * Revision 1.93  2018-08-16 15:24:46  erouault
-- * * dbfopen.c: fix a bug where the end of file character was
-- * written on top of the first character of the first field name
-- * when deleting a field on a .dbf without records.
-- * Fixes https://github.com/OSGeo/gdal/issues/863
-- *
-- * Revision 1.92  2016-12-05 18:44:08  erouault
-- * * dbfopen.c, shapefil.h: write DBF end-of-file character 0x1A by default.
-- * This behaviour can be controlled with the DBFSetWriteEndOfFileChar()
-- * function.
-- *
-- * Revision 1.91  2016-12-05 12:44:05  erouault
-- * * Major overhaul of Makefile build system to use autoconf/automake.
-- *
-- * * Warning fixes in contrib/
-- *
-- * Revision 1.90  2016-12-04 15:30:15  erouault
-- * * shpopen.c, dbfopen.c, shptree.c, shapefil.h: resync with
-- * GDAL Shapefile driver. Mostly cleanups. SHPObject and DBFInfo
-- * structures extended with new members. New functions:
-- * DBFSetLastModifiedDate, SHPOpenLLEx, SHPRestoreSHX,
-- * SHPSetFastModeReadObject
-- *
-- * * sbnsearch.c: new file to implement original ESRI .sbn spatial
-- * index reading. (no write support). New functions:
-- * SBNOpenDiskTree, SBNCloseDiskTree, SBNSearchDiskTree,
-- * SBNSearchDiskTreeInteger, SBNSearchFreeIds
-- *
-- * * Makefile, makefile.vc, CMakeLists.txt, shapelib.def: updates
-- * with new file and symbols.
-- *
-- * * commit: helper script to cvs commit
-- *
-- * Revision 1.89  2011-07-24 05:59:25  fwarmerdam
-- * minimize use of CPLError in favor of SAHooks.Error()
-- *
-- * Revision 1.88  2011-05-13 17:35:17  fwarmerdam
-- * added DBFReorderFields() and DBFAlterFields() functions (from Even)
-- *
-- * Revision 1.87  2011-05-07 22:41:02  fwarmerdam
-- * ensure pending record is flushed when adding a native field (GDAL #4073)
-- *
-- * Revision 1.86  2011-04-17 15:15:29  fwarmerdam
-- * Removed unused variable.
-- *
-- * Revision 1.85  2010-12-06 16:09:34  fwarmerdam
-- * fix buffer read overrun fetching code page (bug 2276)
-- *
-- * Revision 1.84  2009-10-29 19:59:48  fwarmerdam
-- * avoid crash on truncated header (gdal #3093)
-- *
-- * Revision 1.83  2008/11/12 14:28:15  fwarmerdam
-- * DBFCreateField() now works on files with records
-- *
-- * Revision 1.82  2008/11/11 17:47:09  fwarmerdam
-- * added DBFDeleteField() function
-- *
-- * Revision 1.81  2008/01/03 17:48:13  bram
-- * in DBFCreate, use default code page LDID/87 (= 0x57, ANSI)
-- * instead of LDID/3.  This seems to be the same as what ESRI
-- * would be doing by default.
-- *
-- * Revision 1.80  2007/12/30 14:36:39  fwarmerdam
-- * avoid syntax issue with last comment.
-- *
-- * Revision 1.79  2007/12/30 14:35:48  fwarmerdam
-- * Avoid char* / unsigned char* warnings.
-- *
-- * Revision 1.78  2007/12/18 18:28:07  bram
-- * - create hook for client specific atof (bugzilla ticket 1615)
-- * - check for NULL handle before closing cpCPG file, and close after reading.
-- *
-- * Revision 1.77  2007/12/15 20:25:21  bram
-- * dbfopen.c now reads the Code Page information from the DBF file, and exports
-- * this information as a string through the DBFGetCodePage function.  This is
-- * either the number from the LDID header field ("LDID/<number>") or as the
-- * content of an accompanying .CPG file.  When creating a DBF file, the code can
-- * be set using DBFCreateEx.
-- *
-- * Revision 1.76  2007/12/12 22:21:32  bram
-- * DBFClose: check for NULL psDBF handle before trying to close it.
-- *
-- * Revision 1.75  2007/12/06 13:58:19  fwarmerdam
-- * make sure file offset calculations are done in as SAOffset
-- *
-- * Revision 1.74  2007/12/06 07:00:25  fwarmerdam
-- * dbfopen now using SAHooks for fileio
-- *
-- * Revision 1.73  2007/09/03 19:48:11  fwarmerdam
-- * move DBFReadAttribute() static dDoubleField into dbfinfo
-- *
-- * Revision 1.72  2007/09/03 19:34:06  fwarmerdam
-- * Avoid use of static tuple buffer in DBFReadTuple()
-- *
-- * Revision 1.71  2006/06/22 14:37:18  fwarmerdam
-- * avoid memory leak if dbfopen fread fails
-- *
-- * Revision 1.70  2006/06/17 17:47:05  fwarmerdam
-- * use calloc() for dbfinfo in DBFCreate
-- *
-- * Revision 1.69  2006/06/17 15:34:32  fwarmerdam
-- * disallow creating fields wider than 255
-- *
-- * Revision 1.68  2006/06/17 15:12:40  fwarmerdam
-- * Fixed C++ style comments.
-- *
-- * Revision 1.67  2006/06/17 00:24:53  fwarmerdam
-- * Don't treat non-zero decimals values as high order byte for length
-- * for strings.  It causes serious corruption for some files.
-- * http://bugzilla.remotesensing.org/show_bug.cgi?id=1202
-- *
-- * Revision 1.66  2006/03/29 18:26:20  fwarmerdam
-- * fixed bug with size of pachfieldtype in dbfcloneempty
-- *
-- * Revision 1.65  2006/02/15 01:14:30  fwarmerdam
-- * added DBFAddNativeFieldType
-- *
-- * Revision 1.64  2006/02/09 00:29:04  fwarmerdam
-- * Changed to put spaces into string fields that are NULL as
-- * per http://bugzilla.maptools.org/show_bug.cgi?id=316.
-- *
-- * Revision 1.63  2006/01/25 15:35:43  fwarmerdam
-- * check success on DBFFlushRecord
-- *
-- * Revision 1.62  2006/01/10 16:28:03  fwarmerdam
-- * Fixed typo in CPLError.
-- *
-- * Revision 1.61  2006/01/10 16:26:29  fwarmerdam
-- * Push loading record buffer into DBFLoadRecord.
-- * Implement CPL error reporting if USE_CPL defined.
-- *
-- * Revision 1.60  2006/01/05 01:27:27  fwarmerdam
-- * added dbf deletion mark/fetch
-- *
-- * Revision 1.59  2005/03/14 15:20:28  fwarmerdam
-- * Fixed last change.
-- *
-- * Revision 1.58  2005/03/14 15:18:54  fwarmerdam
-- * Treat very wide fields with no decimals as double.  This is
-- * more than 32bit integer fields.
-- *
-- * Revision 1.57  2005/02/10 20:16:54  fwarmerdam
-- * Make the pszStringField buffer for DBFReadAttribute() static char [256]
-- * as per bug 306.
-- *
-- * Revision 1.56  2005/02/10 20:07:56  fwarmerdam
-- * Fixed bug 305 in DBFCloneEmpty() - header length problem.
-- *
-- * Revision 1.55  2004/09/26 20:23:46  fwarmerdam
-- * avoid warnings with rcsid and signed/unsigned stuff
-- *
-- * Revision 1.54  2004/09/15 16:26:10  fwarmerdam
-- * Treat all blank numeric fields as null too.
-- */
--
--#include "shapefil.h"
--
--#include <math.h>
--#include <stdlib.h>
--#include <ctype.h>
--#include <string.h>
--
--#ifdef USE_CPL
--#include "cpl_string.h"
--#else
--
--#if defined(WIN32) || defined(_WIN32)
--#    define STRCASECMP(a,b)         (stricmp(a,b))
--#  else
--#include <strings.h>
--#    define STRCASECMP(a,b)         (strcasecmp(a,b))
--#endif
--
--#if defined(_MSC_VER)
--# if _MSC_VER < 1900
--#     define snprintf _snprintf
--# endif
--#elif defined(WIN32) || defined(_WIN32)
--#  ifndef snprintf
--#     define snprintf _snprintf
--#  endif
--#endif
--
--#define CPLsprintf sprintf
--#define CPLsnprintf snprintf
--#endif
--
--SHP_CVSID("$Id: dbfopen.c,v 1.94 2018-08-16 15:39:07 erouault Exp $")
--
--#ifndef FALSE
--#  define FALSE               0
--#  define TRUE                1
--#endif
--
--/* File header size */
--#define XBASE_FILEHDR_SZ         32
--
--#define HEADER_RECORD_TERMINATOR 0x0D
--
--/* See http://www.manmrk.net/tutorials/database/xbase/dbf.html */
--#define END_OF_FILE_CHARACTER    0x1A
--
--#ifdef USE_CPL
--CPL_INLINE static void CPL_IGNORE_RET_VAL_INT(CPL_UNUSED int unused) {}
--#else
--#define CPL_IGNORE_RET_VAL_INT(x) x
--#endif
--
--#ifdef __cplusplus
--#define STATIC_CAST(type,x) static_cast<type>(x)
--#define REINTERPRET_CAST(type,x) reinterpret_cast<type>(x)
--#define CONST_CAST(type,x) const_cast<type>(x)
--#define SHPLIB_NULLPTR nullptr
--#else
--#define STATIC_CAST(type,x) ((type)(x))
--#define REINTERPRET_CAST(type,x) ((type)(x))
--#define CONST_CAST(type,x) ((type)(x))
--#define SHPLIB_NULLPTR NULL
--#endif
--
--/************************************************************************/
--/*                             SfRealloc()                              */
--/*                                                                      */
--/*      A realloc cover function that will access a NULL pointer as     */
--/*      a valid input.                                                  */
--/************************************************************************/
--
--static void * SfRealloc( void * pMem, int nNewSize )
--
--{
--    if( pMem == SHPLIB_NULLPTR )
--        return malloc(nNewSize);
--    else
--        return realloc(pMem,nNewSize);
--}
--
--/************************************************************************/
--/*                           DBFWriteHeader()                           */
--/*                                                                      */
--/*      This is called to write out the file header, and field          */
--/*      descriptions before writing any actual data records.  This      */
--/*      also computes all the DBFDataSet field offset/size/decimals     */
--/*      and so forth values.                                            */
--/************************************************************************/
--
--static void DBFWriteHeader(DBFHandle psDBF)
--
--{
--    unsigned char     abyHeader[XBASE_FILEHDR_SZ] = { 0 };
--
--    if( !psDBF->bNoHeader )
--        return;
--
--    psDBF->bNoHeader = FALSE;
--
--/* -------------------------------------------------------------------- */
--/*    Initialize the file header information.                         */
--/* -------------------------------------------------------------------- */
--    abyHeader[0] = 0x03;              /* memo field? - just copying   */
--
--    /* write out update date */
--    abyHeader[1] = STATIC_CAST(unsigned char, psDBF->nUpdateYearSince1900);
--    abyHeader[2] = STATIC_CAST(unsigned char, psDBF->nUpdateMonth);
--    abyHeader[3] = STATIC_CAST(unsigned char, psDBF->nUpdateDay);
--
--    /* record count preset at zero */
--
--    abyHeader[8] = STATIC_CAST(unsigned char, psDBF->nHeaderLength % 256);
--    abyHeader[9] = STATIC_CAST(unsigned char, psDBF->nHeaderLength / 256);
--
--    abyHeader[10] = STATIC_CAST(unsigned char, psDBF->nRecordLength % 256);
--    abyHeader[11] = STATIC_CAST(unsigned char, psDBF->nRecordLength / 256);
--
--    abyHeader[29] = STATIC_CAST(unsigned char, psDBF->iLanguageDriver);
--
--/* -------------------------------------------------------------------- */
--/*      Write the initial 32 byte file header, and all the field        */
--/*      descriptions.                                                 */
--/* -------------------------------------------------------------------- */
--    psDBF->sHooks.FSeek( psDBF->fp, 0, 0 );
--    psDBF->sHooks.FWrite( abyHeader, XBASE_FILEHDR_SZ, 1, psDBF->fp );
--    psDBF->sHooks.FWrite( psDBF->pszHeader, XBASE_FLDHDR_SZ, psDBF->nFields,
--                          psDBF->fp );
--
--/* -------------------------------------------------------------------- */
--/*      Write out the newline character if there is room for it.        */
--/* -------------------------------------------------------------------- */
--    if( psDBF->nHeaderLength > XBASE_FLDHDR_SZ*psDBF->nFields +
--                               XBASE_FLDHDR_SZ )
--    {
--        char  cNewline;
--
--        cNewline = HEADER_RECORD_TERMINATOR;
--        psDBF->sHooks.FWrite( &cNewline, 1, 1, psDBF->fp );
--    }
--
--/* -------------------------------------------------------------------- */
--/*      If the file is new, add a EOF character.                        */
--/* -------------------------------------------------------------------- */
--    if( psDBF->nRecords == 0 && psDBF->bWriteEndOfFileChar )
--    {
--        char ch = END_OF_FILE_CHARACTER;
--
--        psDBF->sHooks.FWrite( &ch, 1, 1, psDBF->fp );
--    }
--}
--
--/************************************************************************/
--/*                           DBFFlushRecord()                           */
--/*                                                                      */
--/*      Write out the current record if there is one.                   */
--/************************************************************************/
--
--static int DBFFlushRecord( DBFHandle psDBF )
--
--{
--    SAOffset  nRecordOffset;
--
--    if( psDBF->bCurrentRecordModified && psDBF->nCurrentRecord > -1 )
--    {
--      psDBF->bCurrentRecordModified = FALSE;
--
--      nRecordOffset =
--            psDBF->nRecordLength * STATIC_CAST(SAOffset, psDBF->nCurrentRecord)
--            + psDBF->nHeaderLength;
--
--      if( psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 ) != 0
--            || psDBF->sHooks.FWrite( psDBF->pszCurrentRecord,
--                                     psDBF->nRecordLength,
--                                     1, psDBF->fp ) != 1 )
--        {
--            char szMessage[128];
--            snprintf( szMessage, sizeof(szMessage), "Failure writing DBF record %d.",
--                     psDBF->nCurrentRecord );
--            psDBF->sHooks.Error( szMessage );
--            return FALSE;
--        }
--
--        if( psDBF->nCurrentRecord == psDBF->nRecords - 1 )
--        {
--            if( psDBF->bWriteEndOfFileChar )
--            {
--                char ch = END_OF_FILE_CHARACTER;
--                psDBF->sHooks.FWrite( &ch, 1, 1, psDBF->fp );
--            }
--        }
--    }
--
--    return TRUE;
--}
--
--/************************************************************************/
--/*                           DBFLoadRecord()                            */
--/************************************************************************/
--
--static int DBFLoadRecord( DBFHandle psDBF, int iRecord )
--
--{
--    if( psDBF->nCurrentRecord != iRecord )
--    {
--        SAOffset nRecordOffset;
--
--      if( !DBFFlushRecord( psDBF ) )
--            return FALSE;
--
--      nRecordOffset =
--            psDBF->nRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--      if( psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, SEEK_SET ) != 0 )
--        {
--            char szMessage[128];
--            snprintf( szMessage, sizeof(szMessage), "fseek(%ld) failed on DBF file.",
--                      STATIC_CAST(long, nRecordOffset) );
--            psDBF->sHooks.Error( szMessage );
--            return FALSE;
--        }
--
--      if( psDBF->sHooks.FRead( psDBF->pszCurrentRecord,
--                                 psDBF->nRecordLength, 1, psDBF->fp ) != 1 )
--        {
--            char szMessage[128];
--            snprintf( szMessage, sizeof(szMessage), "fread(%d) failed on DBF file.",
--                     psDBF->nRecordLength );
--            psDBF->sHooks.Error( szMessage );
--            return FALSE;
--        }
--
--      psDBF->nCurrentRecord = iRecord;
--    }
--
--    return TRUE;
--}
--
--/************************************************************************/
--/*                          DBFUpdateHeader()                           */
--/************************************************************************/
--
--void SHPAPI_CALL
--DBFUpdateHeader( DBFHandle psDBF )
--
--{
--    unsigned char             abyFileHeader[XBASE_FILEHDR_SZ];
--
--    if( psDBF->bNoHeader )
--        DBFWriteHeader( psDBF );
--
--    if( !DBFFlushRecord( psDBF ) )
--        return;
--
--    psDBF->sHooks.FSeek( psDBF->fp, 0, 0 );
--    psDBF->sHooks.FRead( abyFileHeader, sizeof(abyFileHeader), 1, psDBF->fp );
--
--    abyFileHeader[1] = STATIC_CAST(unsigned char, psDBF->nUpdateYearSince1900);
--    abyFileHeader[2] = STATIC_CAST(unsigned char, psDBF->nUpdateMonth);
--    abyFileHeader[3] = STATIC_CAST(unsigned char, psDBF->nUpdateDay);
--    abyFileHeader[4] = STATIC_CAST(unsigned char, psDBF->nRecords & 0xFF);
--    abyFileHeader[5] = STATIC_CAST(unsigned char, (psDBF->nRecords>>8) & 0xFF);
--    abyFileHeader[6] = STATIC_CAST(unsigned char, (psDBF->nRecords>>16) & 0xFF);
--    abyFileHeader[7] = STATIC_CAST(unsigned char, (psDBF->nRecords>>24) & 0xFF);
--
--    psDBF->sHooks.FSeek( psDBF->fp, 0, 0 );
--    psDBF->sHooks.FWrite( abyFileHeader, sizeof(abyFileHeader), 1, psDBF->fp );
--
--    psDBF->sHooks.FFlush( psDBF->fp );
--}
--
--/************************************************************************/
--/*                       DBFSetLastModifiedDate()                       */
--/************************************************************************/
--
--void SHPAPI_CALL
--DBFSetLastModifiedDate( DBFHandle psDBF, int nYYSince1900, int nMM, int nDD )
--{
--    psDBF->nUpdateYearSince1900 = nYYSince1900;
--    psDBF->nUpdateMonth = nMM;
--    psDBF->nUpdateDay = nDD;
--}
--
--/************************************************************************/
--/*                              DBFOpen()                               */
--/*                                                                      */
--/*      Open a .dbf file.                                               */
--/************************************************************************/
--
--DBFHandle SHPAPI_CALL
--DBFOpen( const char * pszFilename, const char * pszAccess )
--
--{
--    SAHooks sHooks;
--
--    SASetupDefaultHooks( &sHooks );
--
--    return DBFOpenLL( pszFilename, pszAccess, &sHooks );
--}
--
--/************************************************************************/
--/*                      DBFGetLenWithoutExtension()                     */
--/************************************************************************/
--
--static int DBFGetLenWithoutExtension(const char* pszBasename)
--{
--    int i;
--    int nLen = STATIC_CAST(int, strlen(pszBasename));
--    for( i = nLen-1;
--         i > 0 && pszBasename[i] != '/' && pszBasename[i] != '\\';
--         i-- )
--    {
--        if( pszBasename[i] == '.' )
--        {
--            return i;
--        }
--    }
--    return nLen;
--}
--
--/************************************************************************/
--/*                              DBFOpen()                               */
--/*                                                                      */
--/*      Open a .dbf file.                                               */
--/************************************************************************/
--
--DBFHandle SHPAPI_CALL
--DBFOpenLL( const char * pszFilename, const char * pszAccess, SAHooks *psHooks )
--
--{
--    DBFHandle         psDBF;
--    SAFile            pfCPG;
--    unsigned char     *pabyBuf;
--    int                       nFields, nHeadLen, iField;
--    char              *pszFullname;
--    int                 nBufSize = 500;
--    int                 nLenWithoutExtension;
--
--/* -------------------------------------------------------------------- */
--/*      We only allow the access strings "rb" and "r+".                  */
--/* -------------------------------------------------------------------- */
--    if( strcmp(pszAccess,"r") != 0 && strcmp(pszAccess,"r+") != 0
--        && strcmp(pszAccess,"rb") != 0 && strcmp(pszAccess,"rb+") != 0
--        && strcmp(pszAccess,"r+b") != 0 )
--        return SHPLIB_NULLPTR;
--
--    if( strcmp(pszAccess,"r") == 0 )
--        pszAccess = "rb";
--
--    if( strcmp(pszAccess,"r+") == 0 )
--        pszAccess = "rb+";
--
--/* -------------------------------------------------------------------- */
--/*    Compute the base (layer) name.  If there is any extension       */
--/*    on the passed in filename we will strip it off.                 */
--/* -------------------------------------------------------------------- */
--    nLenWithoutExtension = DBFGetLenWithoutExtension(pszFilename);
--    pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5));
--    memcpy(pszFullname, pszFilename, nLenWithoutExtension);
--    memcpy(pszFullname + nLenWithoutExtension, ".dbf", 5);
--
--    psDBF = STATIC_CAST(DBFHandle, calloc( 1, sizeof(DBFInfo) ));
--    psDBF->fp = psHooks->FOpen( pszFullname, pszAccess );
--    memcpy( &(psDBF->sHooks), psHooks, sizeof(SAHooks) );
--
--    if( psDBF->fp == SHPLIB_NULLPTR )
--    {
--        memcpy(pszFullname + nLenWithoutExtension, ".DBF", 5);
--        psDBF->fp = psDBF->sHooks.FOpen(pszFullname, pszAccess );
--    }
--
--    memcpy(pszFullname + nLenWithoutExtension, ".cpg", 5);
--    pfCPG = psHooks->FOpen( pszFullname, "r" );
--    if( pfCPG == SHPLIB_NULLPTR )
--    {
--        memcpy(pszFullname + nLenWithoutExtension, ".CPG", 5);
--        pfCPG = psHooks->FOpen( pszFullname, "r" );
--    }
--
--    free( pszFullname );
--
--    if( psDBF->fp == SHPLIB_NULLPTR )
--    {
--        free( psDBF );
--        if( pfCPG ) psHooks->FClose( pfCPG );
--        return SHPLIB_NULLPTR;
--    }
--
--    psDBF->bNoHeader = FALSE;
--    psDBF->nCurrentRecord = -1;
--    psDBF->bCurrentRecordModified = FALSE;
--
--/* -------------------------------------------------------------------- */
--/*  Read Table Header info                                              */
--/* -------------------------------------------------------------------- */
--    pabyBuf = STATIC_CAST(unsigned char *, malloc(nBufSize));
--    if( psDBF->sHooks.FRead( pabyBuf, XBASE_FILEHDR_SZ, 1, psDBF->fp ) != 1 )
--    {
--        psDBF->sHooks.FClose( psDBF->fp );
--        if( pfCPG ) psDBF->sHooks.FClose( pfCPG );
--        free( pabyBuf );
--        free( psDBF );
--        return SHPLIB_NULLPTR;
--    }
--
--    DBFSetLastModifiedDate(psDBF, pabyBuf[1], pabyBuf[2], pabyBuf[3]);
--
--    psDBF->nRecords =
--     pabyBuf[4]|(pabyBuf[5]<<8)|(pabyBuf[6]<<16)|((pabyBuf[7]&0x7f)<<24);
--
--    psDBF->nHeaderLength = nHeadLen = pabyBuf[8]|(pabyBuf[9]<<8);
--    psDBF->nRecordLength = pabyBuf[10]|(pabyBuf[11]<<8);
--    psDBF->iLanguageDriver = pabyBuf[29];
--
--    if (psDBF->nRecordLength == 0 || nHeadLen < XBASE_FILEHDR_SZ)
--    {
--        psDBF->sHooks.FClose( psDBF->fp );
--        if( pfCPG ) psDBF->sHooks.FClose( pfCPG );
--        free( pabyBuf );
--        free( psDBF );
--        return SHPLIB_NULLPTR;
--    }
--
--    psDBF->nFields = nFields = (nHeadLen - XBASE_FILEHDR_SZ) / XBASE_FLDHDR_SZ;
--
--    /* coverity[tainted_data] */
--    psDBF->pszCurrentRecord = STATIC_CAST(char *, malloc(psDBF->nRecordLength));
--
--/* -------------------------------------------------------------------- */
--/*  Figure out the code page from the LDID and CPG                      */
--/* -------------------------------------------------------------------- */
--
--    psDBF->pszCodePage = SHPLIB_NULLPTR;
--    if( pfCPG )
--    {
--        size_t n;
--        memset( pabyBuf, 0, nBufSize);
--        psDBF->sHooks.FRead( pabyBuf, nBufSize - 1, 1, pfCPG );
--        n = strcspn( REINTERPRET_CAST(char *, pabyBuf), "\n\r" );
--        if( n > 0 )
--        {
--            pabyBuf[n] = '\0';
--            psDBF->pszCodePage = STATIC_CAST(char *, malloc(n + 1));
--            memcpy( psDBF->pszCodePage, pabyBuf, n + 1 );
--        }
--              psDBF->sHooks.FClose( pfCPG );
--    }
--    if( psDBF->pszCodePage == SHPLIB_NULLPTR && pabyBuf[29] != 0 )
--    {
--        snprintf( REINTERPRET_CAST(char *, pabyBuf), nBufSize, "LDID/%d", psDBF->iLanguageDriver );
--        psDBF->pszCodePage = STATIC_CAST(char *, malloc(strlen(REINTERPRET_CAST(char*, pabyBuf)) + 1));
--        strcpy( psDBF->pszCodePage, REINTERPRET_CAST(char *, pabyBuf) );
--    }
--
--/* -------------------------------------------------------------------- */
--/*  Read in Field Definitions                                           */
--/* -------------------------------------------------------------------- */
--
--    pabyBuf = STATIC_CAST(unsigned char *, SfRealloc(pabyBuf,nHeadLen));
--    psDBF->pszHeader = REINTERPRET_CAST(char *, pabyBuf);
--
--    psDBF->sHooks.FSeek( psDBF->fp, XBASE_FILEHDR_SZ, 0 );
--    if( psDBF->sHooks.FRead( pabyBuf, nHeadLen-XBASE_FILEHDR_SZ, 1,
--                             psDBF->fp ) != 1 )
--    {
--        psDBF->sHooks.FClose( psDBF->fp );
--        free( pabyBuf );
--        free( psDBF->pszCurrentRecord );
--        free( psDBF->pszCodePage );
--        free( psDBF );
--        return SHPLIB_NULLPTR;
--    }
--
--    psDBF->panFieldOffset = STATIC_CAST(int *, malloc(sizeof(int) * nFields));
--    psDBF->panFieldSize = STATIC_CAST(int *, malloc(sizeof(int) * nFields));
--    psDBF->panFieldDecimals = STATIC_CAST(int *, malloc(sizeof(int) * nFields));
--    psDBF->pachFieldType = STATIC_CAST(char *, malloc(sizeof(char) * nFields));
--
--    for( iField = 0; iField < nFields; iField++ )
--    {
--      unsigned char           *pabyFInfo;
--
--      pabyFInfo = pabyBuf+iField*XBASE_FLDHDR_SZ;
--        if( pabyFInfo[0] == HEADER_RECORD_TERMINATOR )
--        {
--            psDBF->nFields = iField;
--            break;
--        }
--
--      if( pabyFInfo[11] == 'N' || pabyFInfo[11] == 'F' )
--      {
--          psDBF->panFieldSize[iField] = pabyFInfo[16];
--          psDBF->panFieldDecimals[iField] = pabyFInfo[17];
--      }
--      else
--      {
--          psDBF->panFieldSize[iField] = pabyFInfo[16];
--          psDBF->panFieldDecimals[iField] = 0;
--
--/*
--** The following seemed to be used sometimes to handle files with long
--** string fields, but in other cases (such as bug 1202) the decimals field
--** just seems to indicate some sort of preferred formatting, not very
--** wide fields.  So I have disabled this code.  FrankW.
--          psDBF->panFieldSize[iField] = pabyFInfo[16] + pabyFInfo[17]*256;
--          psDBF->panFieldDecimals[iField] = 0;
--*/
--      }
--
--      psDBF->pachFieldType[iField] = STATIC_CAST(char, pabyFInfo[11]);
--      if( iField == 0 )
--          psDBF->panFieldOffset[iField] = 1;
--      else
--          psDBF->panFieldOffset[iField] =
--            psDBF->panFieldOffset[iField-1] + psDBF->panFieldSize[iField-1];
--    }
--
--    /* Check that the total width of fields does not exceed the record width */
--    if( psDBF->nFields > 0 &&
--        psDBF->panFieldOffset[psDBF->nFields-1] +
--            psDBF->panFieldSize[psDBF->nFields-1] > psDBF->nRecordLength )
--    {
--        DBFClose( psDBF );
--        return SHPLIB_NULLPTR;
--    }
--
--    DBFSetWriteEndOfFileChar( psDBF, TRUE );
--
--    return( psDBF );
--}
--
--/************************************************************************/
--/*                              DBFClose()                              */
--/************************************************************************/
--
--void SHPAPI_CALL
--DBFClose(DBFHandle psDBF)
--{
--    if( psDBF == SHPLIB_NULLPTR )
--        return;
--
--/* -------------------------------------------------------------------- */
--/*      Write out header if not already written.                        */
--/* -------------------------------------------------------------------- */
--    if( psDBF->bNoHeader )
--        DBFWriteHeader( psDBF );
--
--    CPL_IGNORE_RET_VAL_INT(DBFFlushRecord( psDBF ));
--
--/* -------------------------------------------------------------------- */
--/*      Update last access date, and number of records if we have     */
--/*    write access.                                                   */
--/* -------------------------------------------------------------------- */
--    if( psDBF->bUpdated )
--        DBFUpdateHeader( psDBF );
--
--/* -------------------------------------------------------------------- */
--/*      Close, and free resources.                                      */
--/* -------------------------------------------------------------------- */
--    psDBF->sHooks.FClose( psDBF->fp );
--
--    if( psDBF->panFieldOffset != SHPLIB_NULLPTR )
--    {
--        free( psDBF->panFieldOffset );
--        free( psDBF->panFieldSize );
--        free( psDBF->panFieldDecimals );
--        free( psDBF->pachFieldType );
--    }
--
--    if( psDBF->pszWorkField != SHPLIB_NULLPTR )
--        free( psDBF->pszWorkField );
--
--    free( psDBF->pszHeader );
--    free( psDBF->pszCurrentRecord );
--    free( psDBF->pszCodePage );
--
--    free( psDBF );
--}
--
--/************************************************************************/
--/*                             DBFCreate()                              */
--/*                                                                      */
--/* Create a new .dbf file with default code page LDID/87 (0x57)         */
--/************************************************************************/
--
--DBFHandle SHPAPI_CALL
--DBFCreate( const char * pszFilename )
--
--{
--    return DBFCreateEx( pszFilename, "LDID/87" ); // 0x57
--}
--
--/************************************************************************/
--/*                            DBFCreateEx()                             */
--/*                                                                      */
--/*      Create a new .dbf file.                                         */
--/************************************************************************/
--
--DBFHandle SHPAPI_CALL
--DBFCreateEx( const char * pszFilename, const char* pszCodePage )
--
--{
--    SAHooks sHooks;
--
--    SASetupDefaultHooks( &sHooks );
--
--    return DBFCreateLL( pszFilename, pszCodePage , &sHooks );
--}
--
--/************************************************************************/
--/*                             DBFCreate()                              */
--/*                                                                      */
--/*      Create a new .dbf file.                                         */
--/************************************************************************/
--
--DBFHandle SHPAPI_CALL
--DBFCreateLL( const char * pszFilename, const char * pszCodePage, SAHooks *psHooks )
--
--{
--    DBFHandle psDBF;
--    SAFile    fp;
--    char      *pszFullname;
--    int               ldid = -1;
--    char chZero = '\0';
--    int         nLenWithoutExtension;
--
--/* -------------------------------------------------------------------- */
--/*    Compute the base (layer) name.  If there is any extension       */
--/*    on the passed in filename we will strip it off.                 */
--/* -------------------------------------------------------------------- */
--    nLenWithoutExtension = DBFGetLenWithoutExtension(pszFilename);
--    pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5));
--    memcpy(pszFullname, pszFilename, nLenWithoutExtension);
--    memcpy(pszFullname + nLenWithoutExtension, ".dbf", 5);
--
--/* -------------------------------------------------------------------- */
--/*      Create the file.                                                */
--/* -------------------------------------------------------------------- */
--    fp = psHooks->FOpen( pszFullname, "wb" );
--    if( fp == SHPLIB_NULLPTR )
--    {
--        free( pszFullname );
--        return SHPLIB_NULLPTR;
--    }
--
--    psHooks->FWrite( &chZero, 1, 1, fp );
--    psHooks->FClose( fp );
--
--    fp = psHooks->FOpen( pszFullname, "rb+" );
--    if( fp == SHPLIB_NULLPTR )
--    {
--        free( pszFullname );
--        return SHPLIB_NULLPTR;
--    }
--
--    memcpy(pszFullname + nLenWithoutExtension, ".cpg", 5);
--    if( pszCodePage != SHPLIB_NULLPTR )
--    {
--        if( strncmp( pszCodePage, "LDID/", 5 ) == 0 )
--        {
--            ldid = atoi( pszCodePage + 5 );
--            if( ldid > 255 )
--                ldid = -1; // don't use 0 to indicate out of range as LDID/0 is a valid one
--        }
--        if( ldid < 0 )
--        {
--            SAFile fpCPG = psHooks->FOpen( pszFullname, "w" );
--            psHooks->FWrite( CONST_CAST(void*, STATIC_CAST(const void*, pszCodePage)), strlen(pszCodePage), 1, fpCPG );
--            psHooks->FClose( fpCPG );
--        }
--    }
--    if( pszCodePage == SHPLIB_NULLPTR || ldid >= 0 )
--    {
--        psHooks->Remove( pszFullname );
--    }
--
--    free( pszFullname );
--
--/* -------------------------------------------------------------------- */
--/*    Create the info structure.                                      */
--/* -------------------------------------------------------------------- */
--    psDBF = STATIC_CAST(DBFHandle, calloc(1,sizeof(DBFInfo)));
--
--    memcpy( &(psDBF->sHooks), psHooks, sizeof(SAHooks) );
--    psDBF->fp = fp;
--    psDBF->nRecords = 0;
--    psDBF->nFields = 0;
--    psDBF->nRecordLength = 1;
--    psDBF->nHeaderLength = XBASE_FILEHDR_SZ + 1; /* + 1 for HEADER_RECORD_TERMINATOR */
--
--    psDBF->panFieldOffset = SHPLIB_NULLPTR;
--    psDBF->panFieldSize = SHPLIB_NULLPTR;
--    psDBF->panFieldDecimals = SHPLIB_NULLPTR;
--    psDBF->pachFieldType = SHPLIB_NULLPTR;
--    psDBF->pszHeader = SHPLIB_NULLPTR;
--
--    psDBF->nCurrentRecord = -1;
--    psDBF->bCurrentRecordModified = FALSE;
--    psDBF->pszCurrentRecord = SHPLIB_NULLPTR;
--
--    psDBF->bNoHeader = TRUE;
--
--    psDBF->iLanguageDriver = ldid > 0 ? ldid : 0;
--    psDBF->pszCodePage = SHPLIB_NULLPTR;
--    if( pszCodePage )
--    {
--        psDBF->pszCodePage = STATIC_CAST(char *, malloc( strlen(pszCodePage) + 1 ));
--        strcpy( psDBF->pszCodePage, pszCodePage );
--    }
--    DBFSetLastModifiedDate(psDBF, 95, 7, 26); /* dummy date */
--
--    DBFSetWriteEndOfFileChar(psDBF, TRUE);
--
--    return( psDBF );
--}
--
--/************************************************************************/
--/*                            DBFAddField()                             */
--/*                                                                      */
--/*      Add a field to a newly created .dbf or to an existing one       */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFAddField(DBFHandle psDBF, const char * pszFieldName,
--            DBFFieldType eType, int nWidth, int nDecimals )
--
--{
--    char chNativeType = 'C';
--
--    if( eType == FTLogical )
--        chNativeType = 'L';
--    else if( eType == FTDate )
--      chNativeType = 'D';
--    else if( eType == FTString )
--        chNativeType = 'C';
--    else
--        chNativeType = 'N';
--
--    return DBFAddNativeFieldType( psDBF, pszFieldName, chNativeType,
--                                  nWidth, nDecimals );
--}
--
--/************************************************************************/
--/*                        DBFGetNullCharacter()                         */
--/************************************************************************/
--
--static char DBFGetNullCharacter(char chType)
--{
--    switch (chType)
--    {
--      case 'N':
--      case 'F':
--        return '*';
--      case 'D':
--        return '0';
--      case 'L':
--       return '?';
--      default:
--       return ' ';
--    }
--}
--
--/************************************************************************/
--/*                            DBFAddField()                             */
--/*                                                                      */
--/*      Add a field to a newly created .dbf file before any records     */
--/*      are written.                                                    */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFAddNativeFieldType(DBFHandle psDBF, const char * pszFieldName,
--                      char chType, int nWidth, int nDecimals )
--
--{
--    char      *pszFInfo;
--    int               i;
--    int         nOldRecordLength, nOldHeaderLength;
--    char        *pszRecord;
--    char        chFieldFill;
--    SAOffset    nRecordOffset;
--
--    /* make sure that everything is written in .dbf */
--    if( !DBFFlushRecord( psDBF ) )
--        return -1;
--
--    if( psDBF->nHeaderLength + XBASE_FLDHDR_SZ > 65535 )
--    {
--        char szMessage[128];
--        snprintf( szMessage, sizeof(szMessage),
--                  "Cannot add field %s. Header length limit reached "
--                  "(max 65535 bytes, 2046 fields).",
--                  pszFieldName );
--        psDBF->sHooks.Error( szMessage );
--        return -1;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Do some checking to ensure we can add records to this file.     */
--/* -------------------------------------------------------------------- */
--    if( nWidth < 1 )
--        return -1;
--
--    if( nWidth > XBASE_FLD_MAX_WIDTH )
--        nWidth = XBASE_FLD_MAX_WIDTH;
--
--    if( psDBF->nRecordLength + nWidth > 65535 )
--    {
--        char szMessage[128];
--        snprintf( szMessage, sizeof(szMessage),
--                  "Cannot add field %s. Record length limit reached "
--                  "(max 65535 bytes).",
--                  pszFieldName );
--        psDBF->sHooks.Error( szMessage );
--        return -1;
--    }
--
--    nOldRecordLength = psDBF->nRecordLength;
--    nOldHeaderLength = psDBF->nHeaderLength;
--
--/* -------------------------------------------------------------------- */
--/*      SfRealloc all the arrays larger to hold the additional field      */
--/*      information.                                                    */
--/* -------------------------------------------------------------------- */
--    psDBF->nFields++;
--
--    psDBF->panFieldOffset = STATIC_CAST(int *,
--        SfRealloc( psDBF->panFieldOffset, sizeof(int) * psDBF->nFields ));
--
--    psDBF->panFieldSize = STATIC_CAST(int *,
--        SfRealloc( psDBF->panFieldSize, sizeof(int) * psDBF->nFields ));
--
--    psDBF->panFieldDecimals = STATIC_CAST(int *,
--        SfRealloc( psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields ));
--
--    psDBF->pachFieldType = STATIC_CAST(char *,
--        SfRealloc( psDBF->pachFieldType, sizeof(char) * psDBF->nFields ));
--
--/* -------------------------------------------------------------------- */
--/*      Assign the new field information fields.                        */
--/* -------------------------------------------------------------------- */
--    psDBF->panFieldOffset[psDBF->nFields-1] = psDBF->nRecordLength;
--    psDBF->nRecordLength += nWidth;
--    psDBF->panFieldSize[psDBF->nFields-1] = nWidth;
--    psDBF->panFieldDecimals[psDBF->nFields-1] = nDecimals;
--    psDBF->pachFieldType[psDBF->nFields-1] = chType;
--
--/* -------------------------------------------------------------------- */
--/*      Extend the required header information.                         */
--/* -------------------------------------------------------------------- */
--    psDBF->nHeaderLength += XBASE_FLDHDR_SZ;
--    psDBF->bUpdated = FALSE;
--
--    psDBF->pszHeader = STATIC_CAST(char *, SfRealloc(psDBF->pszHeader,
--                                          psDBF->nFields*XBASE_FLDHDR_SZ));
--
--    pszFInfo = psDBF->pszHeader + XBASE_FLDHDR_SZ * (psDBF->nFields-1);
--
--    for( i = 0; i < XBASE_FLDHDR_SZ; i++ )
--        pszFInfo[i] = '\0';
--
--    strncpy( pszFInfo, pszFieldName, XBASE_FLDNAME_LEN_WRITE );
--
--    pszFInfo[11] = psDBF->pachFieldType[psDBF->nFields-1];
--
--    if( chType == 'C' )
--    {
--        pszFInfo[16] = STATIC_CAST(unsigned char, nWidth % 256);
--        pszFInfo[17] = STATIC_CAST(unsigned char, nWidth / 256);
--    }
--    else
--    {
--        pszFInfo[16] = STATIC_CAST(unsigned char, nWidth);
--        pszFInfo[17] = STATIC_CAST(unsigned char, nDecimals);
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Make the current record buffer appropriately larger.            */
--/* -------------------------------------------------------------------- */
--    psDBF->pszCurrentRecord = STATIC_CAST(char *, SfRealloc(psDBF->pszCurrentRecord,
--                                                 psDBF->nRecordLength));
--
--    /* we're done if dealing with new .dbf */
--    if( psDBF->bNoHeader )
--        return( psDBF->nFields - 1 );
--
--/* -------------------------------------------------------------------- */
--/*      For existing .dbf file, shift records                           */
--/* -------------------------------------------------------------------- */
--
--    /* alloc record */
--    pszRecord = STATIC_CAST(char *, malloc(sizeof(char) * psDBF->nRecordLength));
--
--    chFieldFill = DBFGetNullCharacter(chType);
--
--    for (i = psDBF->nRecords-1; i >= 0; --i)
--    {
--        nRecordOffset = nOldRecordLength * STATIC_CAST(SAOffset, i) + nOldHeaderLength;
--
--        /* load record */
--        psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--        psDBF->sHooks.FRead( pszRecord, nOldRecordLength, 1, psDBF->fp );
--
--        /* set new field's value to NULL */
--        memset(pszRecord + nOldRecordLength, chFieldFill, nWidth);
--
--        nRecordOffset = psDBF->nRecordLength * STATIC_CAST(SAOffset, i) + psDBF->nHeaderLength;
--
--        /* move record to the new place*/
--        psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--        psDBF->sHooks.FWrite( pszRecord, psDBF->nRecordLength, 1, psDBF->fp );
--    }
--
--    if( psDBF->bWriteEndOfFileChar )
--    {
--        char ch = END_OF_FILE_CHARACTER;
--
--        nRecordOffset =
--            psDBF->nRecordLength * STATIC_CAST(SAOffset,psDBF->nRecords) + psDBF->nHeaderLength;
--
--        psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--        psDBF->sHooks.FWrite( &ch, 1, 1, psDBF->fp );
--    }
--
--    /* free record */
--    free(pszRecord);
--
--    /* force update of header with new header, record length and new field */
--    psDBF->bNoHeader = TRUE;
--    DBFUpdateHeader( psDBF );
--
--    psDBF->nCurrentRecord = -1;
--    psDBF->bCurrentRecordModified = FALSE;
--    psDBF->bUpdated = TRUE;
--
--    return( psDBF->nFields-1 );
--}
--
--/************************************************************************/
--/*                          DBFReadAttribute()                          */
--/*                                                                      */
--/*      Read one of the attribute fields of a record.                   */
--/************************************************************************/
--
--static void *DBFReadAttribute(DBFHandle psDBF, int hEntity, int iField,
--                              char chReqType )
--
--{
--    unsigned char     *pabyRec;
--    void      *pReturnField = SHPLIB_NULLPTR;
--
--/* -------------------------------------------------------------------- */
--/*      Verify selection.                                               */
--/* -------------------------------------------------------------------- */
--    if( hEntity < 0 || hEntity >= psDBF->nRecords )
--        return SHPLIB_NULLPTR;
--
--    if( iField < 0 || iField >= psDBF->nFields )
--        return SHPLIB_NULLPTR;
--
--/* -------------------------------------------------------------------- */
--/*    Have we read the record?                                        */
--/* -------------------------------------------------------------------- */
--    if( !DBFLoadRecord( psDBF, hEntity ) )
--        return SHPLIB_NULLPTR;
--
--    pabyRec = REINTERPRET_CAST(unsigned char *, psDBF->pszCurrentRecord);
--
--/* -------------------------------------------------------------------- */
--/*      Ensure we have room to extract the target field.                */
--/* -------------------------------------------------------------------- */
--    if( psDBF->panFieldSize[iField] >= psDBF->nWorkFieldLength )
--    {
--        psDBF->nWorkFieldLength = psDBF->panFieldSize[iField] + 100;
--        if( psDBF->pszWorkField == SHPLIB_NULLPTR )
--            psDBF->pszWorkField = STATIC_CAST(char *, malloc(psDBF->nWorkFieldLength));
--        else
--            psDBF->pszWorkField = STATIC_CAST(char *, realloc(psDBF->pszWorkField,
--                                                   psDBF->nWorkFieldLength));
--    }
--
--/* -------------------------------------------------------------------- */
--/*    Extract the requested field.                                    */
--/* -------------------------------------------------------------------- */
--    memcpy( psDBF->pszWorkField,
--           REINTERPRET_CAST(const char *, pabyRec) + psDBF->panFieldOffset[iField],
--           psDBF->panFieldSize[iField] );
--    psDBF->pszWorkField[psDBF->panFieldSize[iField]] = '\0';
--
--    pReturnField = psDBF->pszWorkField;
--
--/* -------------------------------------------------------------------- */
--/*      Decode the field.                                               */
--/* -------------------------------------------------------------------- */
--    if( chReqType == 'I' )
--    {
--        psDBF->fieldValue.nIntField = atoi(psDBF->pszWorkField);
--
--        pReturnField = &(psDBF->fieldValue.nIntField);
--    }
--    else if( chReqType == 'N' )
--    {
--        psDBF->fieldValue.dfDoubleField = psDBF->sHooks.Atof(psDBF->pszWorkField);
--
--        pReturnField = &(psDBF->fieldValue.dfDoubleField);
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Should we trim white space off the string attribute value?      */
--/* -------------------------------------------------------------------- */
--#ifdef TRIM_DBF_WHITESPACE
--    else
--    {
--        char  *pchSrc, *pchDst;
--
--        pchDst = pchSrc = psDBF->pszWorkField;
--        while( *pchSrc == ' ' )
--            pchSrc++;
--
--        while( *pchSrc != '\0' )
--            *(pchDst++) = *(pchSrc++);
--        *pchDst = '\0';
--
--        while( pchDst != psDBF->pszWorkField && *(--pchDst) == ' ' )
--            *pchDst = '\0';
--    }
--#endif
--
--    return pReturnField;
--}
--
--/************************************************************************/
--/*                        DBFReadIntAttribute()                         */
--/*                                                                      */
--/*      Read an integer attribute.                                      */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFReadIntegerAttribute( DBFHandle psDBF, int iRecord, int iField )
--
--{
--    int       *pnValue;
--
--    pnValue = STATIC_CAST(int *, DBFReadAttribute( psDBF, iRecord, iField, 'I' ));
--
--    if( pnValue == SHPLIB_NULLPTR )
--        return 0;
--    else
--        return *pnValue;
--}
--
--/************************************************************************/
--/*                        DBFReadDoubleAttribute()                      */
--/*                                                                      */
--/*      Read a double attribute.                                        */
--/************************************************************************/
--
--double SHPAPI_CALL
--DBFReadDoubleAttribute( DBFHandle psDBF, int iRecord, int iField )
--
--{
--    double    *pdValue;
--
--    pdValue = STATIC_CAST(double *, DBFReadAttribute( psDBF, iRecord, iField, 'N' ));
--
--    if( pdValue == SHPLIB_NULLPTR )
--        return 0.0;
--    else
--        return *pdValue ;
--}
--
--/************************************************************************/
--/*                        DBFReadStringAttribute()                      */
--/*                                                                      */
--/*      Read a string attribute.                                        */
--/************************************************************************/
--
--const char SHPAPI_CALL1(*)
--DBFReadStringAttribute( DBFHandle psDBF, int iRecord, int iField )
--
--{
--    return STATIC_CAST(const char *, DBFReadAttribute( psDBF, iRecord, iField, 'C' ) );
--}
--
--/************************************************************************/
--/*                        DBFReadLogicalAttribute()                     */
--/*                                                                      */
--/*      Read a logical attribute.                                       */
--/************************************************************************/
--
--const char SHPAPI_CALL1(*)
--DBFReadLogicalAttribute( DBFHandle psDBF, int iRecord, int iField )
--
--{
--    return STATIC_CAST(const char *, DBFReadAttribute( psDBF, iRecord, iField, 'L' ) );
--}
--
--
--/************************************************************************/
--/*                         DBFIsValueNULL()                             */
--/*                                                                      */
--/*      Return TRUE if the passed string is NULL.                       */
--/************************************************************************/
--
--static int DBFIsValueNULL( char chType, const char* pszValue )
--{
--    int i;
--
--    if( pszValue == SHPLIB_NULLPTR )
--        return TRUE;
--
--    switch(chType)
--    {
--      case 'N':
--      case 'F':
--        /*
--        ** We accept all asterisks or all blanks as NULL
--        ** though according to the spec I think it should be all
--        ** asterisks.
--        */
--        if( pszValue[0] == '*' )
--            return TRUE;
--
--        for( i = 0; pszValue[i] != '\0'; i++ )
--        {
--            if( pszValue[i] != ' ' )
--                return FALSE;
--        }
--        return TRUE;
--
--      case 'D':
--        /* NULL date fields have value "00000000" */
--        return strncmp(pszValue,"00000000",8) == 0;
--
--      case 'L':
--        /* NULL boolean fields have value "?" */
--        return pszValue[0] == '?';
--
--      default:
--        /* empty string fields are considered NULL */
--        return strlen(pszValue) == 0;
--    }
--}
--
--/************************************************************************/
--/*                         DBFIsAttributeNULL()                         */
--/*                                                                      */
--/*      Return TRUE if value for field is NULL.                         */
--/*                                                                      */
--/*      Contributed by Jim Matthews.                                    */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFIsAttributeNULL( DBFHandle psDBF, int iRecord, int iField )
--
--{
--    const char        *pszValue;
--
--    pszValue = DBFReadStringAttribute( psDBF, iRecord, iField );
--
--    if( pszValue == SHPLIB_NULLPTR )
--        return TRUE;
--
--    return DBFIsValueNULL( psDBF->pachFieldType[iField], pszValue );
--}
--
--/************************************************************************/
--/*                          DBFGetFieldCount()                          */
--/*                                                                      */
--/*      Return the number of fields in this table.                      */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFGetFieldCount( DBFHandle psDBF )
--
--{
--    return( psDBF->nFields );
--}
--
--/************************************************************************/
--/*                         DBFGetRecordCount()                          */
--/*                                                                      */
--/*      Return the number of records in this table.                     */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFGetRecordCount( DBFHandle psDBF )
--
--{
--    return( psDBF->nRecords );
--}
--
--/************************************************************************/
--/*                          DBFGetFieldInfo()                           */
--/*                                                                      */
--/*      Return any requested information about the field.               */
--/*      pszFieldName must be at least XBASE_FLDNAME_LEN_READ+1 (=12)    */
--/*      bytes long.                                                     */
--/************************************************************************/
--
--DBFFieldType SHPAPI_CALL
--DBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName,
--                 int * pnWidth, int * pnDecimals )
--
--{
--    if( iField < 0 || iField >= psDBF->nFields )
--        return( FTInvalid );
--
--    if( pnWidth != SHPLIB_NULLPTR )
--        *pnWidth = psDBF->panFieldSize[iField];
--
--    if( pnDecimals != SHPLIB_NULLPTR )
--        *pnDecimals = psDBF->panFieldDecimals[iField];
--
--    if( pszFieldName != SHPLIB_NULLPTR )
--    {
--      int     i;
--
--      strncpy( pszFieldName, STATIC_CAST(char *,psDBF->pszHeader)+iField*XBASE_FLDHDR_SZ,
--                 XBASE_FLDNAME_LEN_READ );
--      pszFieldName[XBASE_FLDNAME_LEN_READ] = '\0';
--      for( i = XBASE_FLDNAME_LEN_READ - 1; i > 0 && pszFieldName[i] == ' '; i-- )
--          pszFieldName[i] = '\0';
--    }
--
--    if ( psDBF->pachFieldType[iField] == 'L' )
--      return( FTLogical );
--
--    else if( psDBF->pachFieldType[iField] == 'D' )
--      return( FTDate );
--
--    else if( psDBF->pachFieldType[iField] == 'N'
--             || psDBF->pachFieldType[iField] == 'F' )
--    {
--      if( psDBF->panFieldDecimals[iField] > 0
--            || psDBF->panFieldSize[iField] >= 10 )
--          return( FTDouble );
--      else
--          return( FTInteger );
--    }
--    else
--    {
--      return( FTString );
--    }
--}
--
--/************************************************************************/
--/*                         DBFWriteAttribute()                          */
--/*                                                                    */
--/*    Write an attribute record to the file.                          */
--/************************************************************************/
--
--static int DBFWriteAttribute(DBFHandle psDBF, int hEntity, int iField,
--                           void * pValue )
--
--{
--    int               i, j, nRetResult = TRUE;
--    unsigned char     *pabyRec;
--    char      szSField[XBASE_FLD_MAX_WIDTH+1], szFormat[20];
--
--/* -------------------------------------------------------------------- */
--/*    Is this a valid record?                                         */
--/* -------------------------------------------------------------------- */
--    if( hEntity < 0 || hEntity > psDBF->nRecords )
--        return( FALSE );
--
--    if( psDBF->bNoHeader )
--        DBFWriteHeader(psDBF);
--
--/* -------------------------------------------------------------------- */
--/*      Is this a brand new record?                                     */
--/* -------------------------------------------------------------------- */
--    if( hEntity == psDBF->nRecords )
--    {
--      if( !DBFFlushRecord( psDBF ) )
--            return FALSE;
--
--      psDBF->nRecords++;
--      for( i = 0; i < psDBF->nRecordLength; i++ )
--          psDBF->pszCurrentRecord[i] = ' ';
--
--      psDBF->nCurrentRecord = hEntity;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Is this an existing record, but different than the last one     */
--/*      we accessed?                                                    */
--/* -------------------------------------------------------------------- */
--    if( !DBFLoadRecord( psDBF, hEntity ) )
--        return FALSE;
--
--    pabyRec = REINTERPRET_CAST(unsigned char *,psDBF->pszCurrentRecord);
--
--    psDBF->bCurrentRecordModified = TRUE;
--    psDBF->bUpdated = TRUE;
--
--/* -------------------------------------------------------------------- */
--/*      Translate NULL value to valid DBF file representation.          */
--/*                                                                      */
--/*      Contributed by Jim Matthews.                                    */
--/* -------------------------------------------------------------------- */
--    if( pValue == SHPLIB_NULLPTR )
--    {
--        memset( pabyRec+psDBF->panFieldOffset[iField],
--                DBFGetNullCharacter(psDBF->pachFieldType[iField]),
--                psDBF->panFieldSize[iField] );
--        return TRUE;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Assign all the record fields.                                   */
--/* -------------------------------------------------------------------- */
--    switch( psDBF->pachFieldType[iField] )
--    {
--      case 'D':
--      case 'N':
--      case 'F':
--      {
--        int           nWidth = psDBF->panFieldSize[iField];
--
--        if( STATIC_CAST(int,sizeof(szSField))-2 < nWidth )
--            nWidth = sizeof(szSField)-2;
--
--        snprintf( szFormat, sizeof(szFormat), "%%%d.%df",
--                    nWidth, psDBF->panFieldDecimals[iField] );
--        CPLsnprintf(szSField, sizeof(szSField), szFormat, *STATIC_CAST(double *, pValue) );
--        szSField[sizeof(szSField)-1] = '\0';
--        if( STATIC_CAST(int,strlen(szSField)) > psDBF->panFieldSize[iField] )
--        {
--            szSField[psDBF->panFieldSize[iField]] = '\0';
--            nRetResult = FALSE;
--        }
--        strncpy(REINTERPRET_CAST(char *, pabyRec+psDBF->panFieldOffset[iField]),
--            szSField, strlen(szSField) );
--        break;
--      }
--
--      case 'L':
--        if (psDBF->panFieldSize[iField] >= 1  &&
--            (*STATIC_CAST(char*,pValue) == 'F' || *STATIC_CAST(char*,pValue) == 'T'))
--            *(pabyRec+psDBF->panFieldOffset[iField]) = *STATIC_CAST(char*,pValue);
--        break;
--
--      default:
--      if( STATIC_CAST(int, strlen(STATIC_CAST(char *,pValue))) > psDBF->panFieldSize[iField] )
--        {
--          j = psDBF->panFieldSize[iField];
--            nRetResult = FALSE;
--        }
--      else
--        {
--            memset( pabyRec+psDBF->panFieldOffset[iField], ' ',
--                    psDBF->panFieldSize[iField] );
--          j = STATIC_CAST(int, strlen(STATIC_CAST(char *,pValue)));
--        }
--
--      strncpy(REINTERPRET_CAST(char *, pabyRec+psDBF->panFieldOffset[iField]),
--              STATIC_CAST(const char *, pValue), j );
--      break;
--    }
--
--    return( nRetResult );
--}
--
--/************************************************************************/
--/*                     DBFWriteAttributeDirectly()                      */
--/*                                                                      */
--/*      Write an attribute record to the file, but without any          */
--/*      reformatting based on type.  The provided buffer is written     */
--/*      as is to the field position in the record.                      */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteAttributeDirectly(DBFHandle psDBF, int hEntity, int iField,
--                              void * pValue )
--
--{
--    int                       i, j;
--    unsigned char     *pabyRec;
--
--/* -------------------------------------------------------------------- */
--/*    Is this a valid record?                                         */
--/* -------------------------------------------------------------------- */
--    if( hEntity < 0 || hEntity > psDBF->nRecords )
--        return( FALSE );
--
--    if( psDBF->bNoHeader )
--        DBFWriteHeader(psDBF);
--
--/* -------------------------------------------------------------------- */
--/*      Is this a brand new record?                                     */
--/* -------------------------------------------------------------------- */
--    if( hEntity == psDBF->nRecords )
--    {
--      if( !DBFFlushRecord( psDBF ) )
--            return FALSE;
--
--      psDBF->nRecords++;
--      for( i = 0; i < psDBF->nRecordLength; i++ )
--          psDBF->pszCurrentRecord[i] = ' ';
--
--      psDBF->nCurrentRecord = hEntity;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Is this an existing record, but different than the last one     */
--/*      we accessed?                                                    */
--/* -------------------------------------------------------------------- */
--    if( !DBFLoadRecord( psDBF, hEntity ) )
--        return FALSE;
--
--    pabyRec = REINTERPRET_CAST(unsigned char *, psDBF->pszCurrentRecord);
--
--/* -------------------------------------------------------------------- */
--/*      Assign all the record fields.                                   */
--/* -------------------------------------------------------------------- */
--    if( STATIC_CAST(int, strlen(STATIC_CAST(char *, pValue))) > psDBF->panFieldSize[iField] )
--        j = psDBF->panFieldSize[iField];
--    else
--    {
--        memset( pabyRec+psDBF->panFieldOffset[iField], ' ',
--                psDBF->panFieldSize[iField] );
--        j = STATIC_CAST(int, strlen(STATIC_CAST(char *, pValue)));
--    }
--
--    strncpy(REINTERPRET_CAST(char *, pabyRec+psDBF->panFieldOffset[iField]),
--            STATIC_CAST(const char *, pValue), j );
--
--    psDBF->bCurrentRecordModified = TRUE;
--    psDBF->bUpdated = TRUE;
--
--    return( TRUE );
--}
--
--/************************************************************************/
--/*                      DBFWriteDoubleAttribute()                       */
--/*                                                                      */
--/*      Write a double attribute.                                       */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteDoubleAttribute( DBFHandle psDBF, int iRecord, int iField,
--                         double dValue )
--
--{
--    return( DBFWriteAttribute( psDBF, iRecord, iField, STATIC_CAST(void *, &dValue) ) );
--}
--
--/************************************************************************/
--/*                      DBFWriteIntegerAttribute()                      */
--/*                                                                      */
--/*      Write a integer attribute.                                      */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteIntegerAttribute( DBFHandle psDBF, int iRecord, int iField,
--                          int nValue )
--
--{
--    double    dValue = nValue;
--
--    return( DBFWriteAttribute( psDBF, iRecord, iField, STATIC_CAST(void *, &dValue) ) );
--}
--
--/************************************************************************/
--/*                      DBFWriteStringAttribute()                       */
--/*                                                                      */
--/*      Write a string attribute.                                       */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteStringAttribute( DBFHandle psDBF, int iRecord, int iField,
--                         const char * pszValue )
--
--{
--    return( DBFWriteAttribute( psDBF, iRecord, iField, STATIC_CAST(void *, CONST_CAST(char*, pszValue))) );
--}
--
--/************************************************************************/
--/*                      DBFWriteNULLAttribute()                         */
--/*                                                                      */
--/*      Write a string attribute.                                       */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteNULLAttribute( DBFHandle psDBF, int iRecord, int iField )
--
--{
--    return( DBFWriteAttribute( psDBF, iRecord, iField, SHPLIB_NULLPTR ) );
--}
--
--/************************************************************************/
--/*                      DBFWriteLogicalAttribute()                      */
--/*                                                                      */
--/*      Write a logical attribute.                                      */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteLogicalAttribute( DBFHandle psDBF, int iRecord, int iField,
--                     const char lValue)
--
--{
--    return( DBFWriteAttribute( psDBF, iRecord, iField, STATIC_CAST(void *, CONST_CAST(char*, &lValue)) ) );
--}
--
--/************************************************************************/
--/*                         DBFWriteTuple()                              */
--/*                                                                    */
--/*    Write an attribute record to the file.                          */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFWriteTuple(DBFHandle psDBF, int hEntity, void * pRawTuple )
--
--{
--    int                       i;
--    unsigned char     *pabyRec;
--
--/* -------------------------------------------------------------------- */
--/*    Is this a valid record?                                         */
--/* -------------------------------------------------------------------- */
--    if( hEntity < 0 || hEntity > psDBF->nRecords )
--        return( FALSE );
--
--    if( psDBF->bNoHeader )
--        DBFWriteHeader(psDBF);
--
--/* -------------------------------------------------------------------- */
--/*      Is this a brand new record?                                     */
--/* -------------------------------------------------------------------- */
--    if( hEntity == psDBF->nRecords )
--    {
--      if( !DBFFlushRecord( psDBF ) )
--            return FALSE;
--
--      psDBF->nRecords++;
--      for( i = 0; i < psDBF->nRecordLength; i++ )
--          psDBF->pszCurrentRecord[i] = ' ';
--
--      psDBF->nCurrentRecord = hEntity;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Is this an existing record, but different than the last one     */
--/*      we accessed?                                                    */
--/* -------------------------------------------------------------------- */
--    if( !DBFLoadRecord( psDBF, hEntity ) )
--        return FALSE;
--
--    pabyRec = REINTERPRET_CAST(unsigned char *, psDBF->pszCurrentRecord);
--
--    memcpy ( pabyRec, pRawTuple,  psDBF->nRecordLength );
--
--    psDBF->bCurrentRecordModified = TRUE;
--    psDBF->bUpdated = TRUE;
--
--    return( TRUE );
--}
--
--/************************************************************************/
--/*                            DBFReadTuple()                            */
--/*                                                                      */
--/*      Read a complete record.  Note that the result is only valid     */
--/*      till the next record read for any reason.                       */
--/************************************************************************/
--
--const char SHPAPI_CALL1(*)
--DBFReadTuple(DBFHandle psDBF, int hEntity )
--
--{
--    if( hEntity < 0 || hEntity >= psDBF->nRecords )
--        return SHPLIB_NULLPTR;
--
--    if( !DBFLoadRecord( psDBF, hEntity ) )
--        return SHPLIB_NULLPTR;
--
--    return STATIC_CAST(const char *, psDBF->pszCurrentRecord);
--}
--
--/************************************************************************/
--/*                          DBFCloneEmpty()                              */
--/*                                                                      */
--/*      Read one of the attribute fields of a record.                   */
--/************************************************************************/
--
--DBFHandle SHPAPI_CALL
--DBFCloneEmpty(DBFHandle psDBF, const char * pszFilename )
--{
--    DBFHandle newDBF;
--
--   newDBF = DBFCreateEx ( pszFilename, psDBF->pszCodePage );
--   if ( newDBF == SHPLIB_NULLPTR ) return SHPLIB_NULLPTR;
--
--   newDBF->nFields = psDBF->nFields;
--   newDBF->nRecordLength = psDBF->nRecordLength;
--   newDBF->nHeaderLength = psDBF->nHeaderLength;
--
--   if( psDBF->pszHeader )
--   {
--        newDBF->pszHeader = STATIC_CAST(char *, malloc ( XBASE_FLDHDR_SZ * psDBF->nFields ));
--        memcpy ( newDBF->pszHeader, psDBF->pszHeader, XBASE_FLDHDR_SZ * psDBF->nFields );
--   }
--
--   newDBF->panFieldOffset = STATIC_CAST(int *, malloc ( sizeof(int) * psDBF->nFields ));
--   memcpy ( newDBF->panFieldOffset, psDBF->panFieldOffset, sizeof(int) * psDBF->nFields );
--   newDBF->panFieldSize = STATIC_CAST(int *, malloc ( sizeof(int) * psDBF->nFields ));
--   memcpy ( newDBF->panFieldSize, psDBF->panFieldSize, sizeof(int) * psDBF->nFields );
--   newDBF->panFieldDecimals = STATIC_CAST(int *, malloc ( sizeof(int) * psDBF->nFields ));
--   memcpy ( newDBF->panFieldDecimals, psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields );
--   newDBF->pachFieldType = STATIC_CAST(char *, malloc ( sizeof(char) * psDBF->nFields ));
--   memcpy ( newDBF->pachFieldType, psDBF->pachFieldType, sizeof(char)*psDBF->nFields );
--
--   newDBF->bNoHeader = TRUE;
--   newDBF->bUpdated = TRUE;
--   newDBF->bWriteEndOfFileChar = psDBF->bWriteEndOfFileChar;
--
--   DBFWriteHeader ( newDBF );
--   DBFClose ( newDBF );
--
--   newDBF = DBFOpen ( pszFilename, "rb+" );
--   newDBF->bWriteEndOfFileChar = psDBF->bWriteEndOfFileChar;
--
--   return ( newDBF );
--}
--
--/************************************************************************/
--/*                       DBFGetNativeFieldType()                        */
--/*                                                                      */
--/*      Return the DBase field type for the specified field.            */
--/*                                                                      */
--/*      Value can be one of: 'C' (String), 'D' (Date), 'F' (Float),     */
--/*                           'N' (Numeric, with or without decimal),    */
--/*                           'L' (Logical),                             */
--/*                           'M' (Memo: 10 digits .DBT block ptr)       */
--/************************************************************************/
--
--char SHPAPI_CALL
--DBFGetNativeFieldType( DBFHandle psDBF, int iField )
--
--{
--    if( iField >=0 && iField < psDBF->nFields )
--        return psDBF->pachFieldType[iField];
--
--    return  ' ';
--}
--
--/************************************************************************/
--/*                          DBFGetFieldIndex()                          */
--/*                                                                      */
--/*      Get the index number for a field in a .dbf file.                */
--/*                                                                      */
--/*      Contributed by Jim Matthews.                                    */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName)
--
--{
--    char          name[XBASE_FLDNAME_LEN_READ+1];
--    int           i;
--
--    for( i = 0; i < DBFGetFieldCount(psDBF); i++ )
--    {
--        DBFGetFieldInfo( psDBF, i, name, SHPLIB_NULLPTR, SHPLIB_NULLPTR );
--        if(!STRCASECMP(pszFieldName,name))
--            return(i);
--    }
--    return(-1);
--}
--
--/************************************************************************/
--/*                         DBFIsRecordDeleted()                         */
--/*                                                                      */
--/*      Returns TRUE if the indicated record is deleted, otherwise      */
--/*      it returns FALSE.                                               */
--/************************************************************************/
--
--int SHPAPI_CALL DBFIsRecordDeleted( DBFHandle psDBF, int iShape )
--
--{
--/* -------------------------------------------------------------------- */
--/*      Verify selection.                                               */
--/* -------------------------------------------------------------------- */
--    if( iShape < 0 || iShape >= psDBF->nRecords )
--        return TRUE;
--
--/* -------------------------------------------------------------------- */
--/*    Have we read the record?                                        */
--/* -------------------------------------------------------------------- */
--    if( !DBFLoadRecord( psDBF, iShape ) )
--        return FALSE;
--
--/* -------------------------------------------------------------------- */
--/*      '*' means deleted.                                              */
--/* -------------------------------------------------------------------- */
--    return psDBF->pszCurrentRecord[0] == '*';
--}
--
--/************************************************************************/
--/*                        DBFMarkRecordDeleted()                        */
--/************************************************************************/
--
--int SHPAPI_CALL DBFMarkRecordDeleted( DBFHandle psDBF, int iShape,
--                                      int bIsDeleted )
--
--{
--    char chNewFlag;
--
--/* -------------------------------------------------------------------- */
--/*      Verify selection.                                               */
--/* -------------------------------------------------------------------- */
--    if( iShape < 0 || iShape >= psDBF->nRecords )
--        return FALSE;
--
--/* -------------------------------------------------------------------- */
--/*      Is this an existing record, but different than the last one     */
--/*      we accessed?                                                    */
--/* -------------------------------------------------------------------- */
--    if( !DBFLoadRecord( psDBF, iShape ) )
--        return FALSE;
--
--/* -------------------------------------------------------------------- */
--/*      Assign value, marking record as dirty if it changes.            */
--/* -------------------------------------------------------------------- */
--    if( bIsDeleted )
--        chNewFlag = '*';
--    else
--        chNewFlag = ' ';
--
--    if( psDBF->pszCurrentRecord[0] != chNewFlag )
--    {
--        psDBF->bCurrentRecordModified = TRUE;
--        psDBF->bUpdated = TRUE;
--        psDBF->pszCurrentRecord[0] = chNewFlag;
--    }
--
--    return TRUE;
--}
--
--/************************************************************************/
--/*                            DBFGetCodePage                            */
--/************************************************************************/
--
--const char SHPAPI_CALL1(*)
--DBFGetCodePage(DBFHandle psDBF )
--{
--    if( psDBF == SHPLIB_NULLPTR )
--        return SHPLIB_NULLPTR;
--    return psDBF->pszCodePage;
--}
--
--/************************************************************************/
--/*                          DBFDeleteField()                            */
--/*                                                                      */
--/*      Remove a field from a .dbf file                                 */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFDeleteField(DBFHandle psDBF, int iField)
--{
--    int nOldRecordLength, nOldHeaderLength;
--    int nDeletedFieldOffset, nDeletedFieldSize;
--    SAOffset nRecordOffset;
--    char* pszRecord;
--    int i, iRecord;
--
--    if (iField < 0 || iField >= psDBF->nFields)
--        return FALSE;
--
--    /* make sure that everything is written in .dbf */
--    if( !DBFFlushRecord( psDBF ) )
--        return FALSE;
--
--    /* get information about field to be deleted */
--    nOldRecordLength = psDBF->nRecordLength;
--    nOldHeaderLength = psDBF->nHeaderLength;
--    nDeletedFieldOffset = psDBF->panFieldOffset[iField];
--    nDeletedFieldSize = psDBF->panFieldSize[iField];
--
--    /* update fields info */
--    for (i = iField + 1; i < psDBF->nFields; i++)
--    {
--        psDBF->panFieldOffset[i-1] = psDBF->panFieldOffset[i] - nDeletedFieldSize;
--        psDBF->panFieldSize[i-1] = psDBF->panFieldSize[i];
--        psDBF->panFieldDecimals[i-1] = psDBF->panFieldDecimals[i];
--        psDBF->pachFieldType[i-1] = psDBF->pachFieldType[i];
--    }
--
--    /* resize fields arrays */
--    psDBF->nFields--;
--
--    psDBF->panFieldOffset = STATIC_CAST(int *,
--        SfRealloc( psDBF->panFieldOffset, sizeof(int) * psDBF->nFields ));
--
--    psDBF->panFieldSize = STATIC_CAST(int *,
--        SfRealloc( psDBF->panFieldSize, sizeof(int) * psDBF->nFields ));
--
--    psDBF->panFieldDecimals = STATIC_CAST(int *,
--        SfRealloc( psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields ));
--
--    psDBF->pachFieldType = STATIC_CAST(char *,
--        SfRealloc( psDBF->pachFieldType, sizeof(char) * psDBF->nFields ));
--
--    /* update header information */
--    psDBF->nHeaderLength -= XBASE_FLDHDR_SZ;
--    psDBF->nRecordLength -= nDeletedFieldSize;
--
--    /* overwrite field information in header */
--    memmove(psDBF->pszHeader + iField*XBASE_FLDHDR_SZ,
--           psDBF->pszHeader + (iField+1)*XBASE_FLDHDR_SZ,
--           sizeof(char) * (psDBF->nFields - iField)*XBASE_FLDHDR_SZ);
--
--    psDBF->pszHeader = STATIC_CAST(char *, SfRealloc(psDBF->pszHeader,
--                                          psDBF->nFields*XBASE_FLDHDR_SZ));
--
--    /* update size of current record appropriately */
--    psDBF->pszCurrentRecord = STATIC_CAST(char *, SfRealloc(psDBF->pszCurrentRecord,
--                                                 psDBF->nRecordLength));
--
--    /* we're done if we're dealing with not yet created .dbf */
--    if ( psDBF->bNoHeader && psDBF->nRecords == 0 )
--        return TRUE;
--
--    /* force update of header with new header and record length */
--    psDBF->bNoHeader = TRUE;
--    DBFUpdateHeader( psDBF );
--
--    /* alloc record */
--    pszRecord = STATIC_CAST(char *, malloc(sizeof(char) * nOldRecordLength));
--
--    /* shift records to their new positions */
--    for (iRecord = 0; iRecord < psDBF->nRecords; iRecord++)
--    {
--        nRecordOffset =
--            nOldRecordLength * STATIC_CAST(SAOffset,iRecord) + nOldHeaderLength;
--
--        /* load record */
--        psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--        psDBF->sHooks.FRead( pszRecord, nOldRecordLength, 1, psDBF->fp );
--
--        nRecordOffset =
--            psDBF->nRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--        /* move record in two steps */
--        psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--        psDBF->sHooks.FWrite( pszRecord, nDeletedFieldOffset, 1, psDBF->fp );
--        psDBF->sHooks.FWrite( pszRecord + nDeletedFieldOffset + nDeletedFieldSize,
--                              nOldRecordLength - nDeletedFieldOffset - nDeletedFieldSize,
--                              1, psDBF->fp );
--
--    }
--
--    if( psDBF->bWriteEndOfFileChar )
--    {
--        char ch = END_OF_FILE_CHARACTER;
--        SAOffset nEOFOffset =
--            psDBF->nRecordLength * STATIC_CAST(SAOffset,psDBF->nRecords) + psDBF->nHeaderLength;
--
--        psDBF->sHooks.FSeek( psDBF->fp, nEOFOffset, 0 );
--        psDBF->sHooks.FWrite( &ch, 1, 1, psDBF->fp );
--    }
--
--    /* TODO: truncate file */
--
--    /* free record */
--    free(pszRecord);
--
--    psDBF->nCurrentRecord = -1;
--    psDBF->bCurrentRecordModified = FALSE;
--    psDBF->bUpdated = TRUE;
--
--    return TRUE;
--}
--
--/************************************************************************/
--/*                          DBFReorderFields()                          */
--/*                                                                      */
--/*      Reorder the fields of a .dbf file                               */
--/*                                                                      */
--/* panMap must be exactly psDBF->nFields long and be a permutation      */
--/* of [0, psDBF->nFields-1]. This assumption will not be asserted in the*/
--/* code of DBFReorderFields.                                            */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFReorderFields( DBFHandle psDBF, int* panMap )
--{
--    SAOffset nRecordOffset;
--    int      i, iRecord;
--    int     *panFieldOffsetNew;
--    int     *panFieldSizeNew;
--    int     *panFieldDecimalsNew;
--    char    *pachFieldTypeNew;
--    char    *pszHeaderNew;
--    char    *pszRecord;
--    char    *pszRecordNew;
--
--    if ( psDBF->nFields == 0 )
--        return TRUE;
--
--    /* make sure that everything is written in .dbf */
--    if( !DBFFlushRecord( psDBF ) )
--        return FALSE;
--
--    /* a simple malloc() would be enough, but calloc() helps clang static analyzer */
--    panFieldOffsetNew = STATIC_CAST(int *, calloc(sizeof(int), psDBF->nFields));
--    panFieldSizeNew = STATIC_CAST(int *, calloc(sizeof(int),  psDBF->nFields));
--    panFieldDecimalsNew = STATIC_CAST(int *, calloc(sizeof(int), psDBF->nFields));
--    pachFieldTypeNew = STATIC_CAST(char *, calloc(sizeof(char), psDBF->nFields));
--    pszHeaderNew = STATIC_CAST(char*, malloc(sizeof(char) * XBASE_FLDHDR_SZ * 
--                                  psDBF->nFields));
--
--    /* shuffle fields definitions */
--    for(i=0; i < psDBF->nFields; i++)
--    {
--        panFieldSizeNew[i] = psDBF->panFieldSize[panMap[i]];
--        panFieldDecimalsNew[i] = psDBF->panFieldDecimals[panMap[i]];
--        pachFieldTypeNew[i] = psDBF->pachFieldType[panMap[i]];
--        memcpy(pszHeaderNew + i * XBASE_FLDHDR_SZ,
--               psDBF->pszHeader + panMap[i] * XBASE_FLDHDR_SZ, XBASE_FLDHDR_SZ);
--    }
--    panFieldOffsetNew[0] = 1;
--    for(i=1; i < psDBF->nFields; i++)
--    {
--        panFieldOffsetNew[i] = panFieldOffsetNew[i - 1] + panFieldSizeNew[i - 1];
--    }
--
--    free(psDBF->pszHeader);
--    psDBF->pszHeader = pszHeaderNew;
--
--    /* we're done if we're dealing with not yet created .dbf */
--    if ( !(psDBF->bNoHeader && psDBF->nRecords == 0) )
--    {
--        /* force update of header with new header and record length */
--        psDBF->bNoHeader = TRUE;
--        DBFUpdateHeader( psDBF );
--
--        /* alloc record */
--        pszRecord = STATIC_CAST(char *, malloc(sizeof(char) * psDBF->nRecordLength));
--        pszRecordNew = STATIC_CAST(char *, malloc(sizeof(char) * psDBF->nRecordLength));
--
--        /* shuffle fields in records */
--        for (iRecord = 0; iRecord < psDBF->nRecords; iRecord++)
--        {
--            nRecordOffset =
--                psDBF->nRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--            /* load record */
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FRead( pszRecord, psDBF->nRecordLength, 1, psDBF->fp );
--
--            pszRecordNew[0] = pszRecord[0];
--
--            for(i=0; i < psDBF->nFields; i++)
--            {
--                memcpy(pszRecordNew + panFieldOffsetNew[i],
--                       pszRecord + psDBF->panFieldOffset[panMap[i]],
--                       psDBF->panFieldSize[panMap[i]]);
--            }
--
--            /* write record */
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FWrite( pszRecordNew, psDBF->nRecordLength, 1, psDBF->fp );
--        }
--
--        /* free record */
--        free(pszRecord);
--        free(pszRecordNew);
--    }
--
--    free(psDBF->panFieldOffset);
--    free(psDBF->panFieldSize);
--    free(psDBF->panFieldDecimals);
--    free(psDBF->pachFieldType);
--
--    psDBF->panFieldOffset = panFieldOffsetNew;
--    psDBF->panFieldSize = panFieldSizeNew;
--    psDBF->panFieldDecimals =panFieldDecimalsNew;
--    psDBF->pachFieldType = pachFieldTypeNew;
--
--    psDBF->nCurrentRecord = -1;
--    psDBF->bCurrentRecordModified = FALSE;
--    psDBF->bUpdated = TRUE;
--
--    return TRUE;
--}
--
--
--/************************************************************************/
--/*                          DBFAlterFieldDefn()                         */
--/*                                                                      */
--/*      Alter a field definition in a .dbf file                         */
--/************************************************************************/
--
--int SHPAPI_CALL
--DBFAlterFieldDefn( DBFHandle psDBF, int iField, const char * pszFieldName,
--                    char chType, int nWidth, int nDecimals )
--{
--    int   i;
--    int   iRecord;
--    int   nOffset;
--    int   nOldWidth;
--    int   nOldRecordLength;
--    SAOffset  nRecordOffset;
--    char* pszFInfo;
--    char  chOldType;
--    int   bIsNULL;
--    char chFieldFill;
--
--    if (iField < 0 || iField >= psDBF->nFields)
--        return FALSE;
--
--    /* make sure that everything is written in .dbf */
--    if( !DBFFlushRecord( psDBF ) )
--        return FALSE;
--
--    chFieldFill = DBFGetNullCharacter(chType);
--
--    chOldType = psDBF->pachFieldType[iField];
--    nOffset = psDBF->panFieldOffset[iField];
--    nOldWidth = psDBF->panFieldSize[iField];
--    nOldRecordLength = psDBF->nRecordLength;
--
--/* -------------------------------------------------------------------- */
--/*      Do some checking to ensure we can add records to this file.     */
--/* -------------------------------------------------------------------- */
--    if( nWidth < 1 )
--        return -1;
--
--    if( nWidth > XBASE_FLD_MAX_WIDTH )
--        nWidth = XBASE_FLD_MAX_WIDTH;
--
--/* -------------------------------------------------------------------- */
--/*      Assign the new field information fields.                        */
--/* -------------------------------------------------------------------- */
--    psDBF->panFieldSize[iField] = nWidth;
--    psDBF->panFieldDecimals[iField] = nDecimals;
--    psDBF->pachFieldType[iField] = chType;
--
--/* -------------------------------------------------------------------- */
--/*      Update the header information.                                  */
--/* -------------------------------------------------------------------- */
--    pszFInfo = psDBF->pszHeader + XBASE_FLDHDR_SZ * iField;
--
--    for( i = 0; i < XBASE_FLDHDR_SZ; i++ )
--        pszFInfo[i] = '\0';
--
--    strncpy( pszFInfo, pszFieldName, XBASE_FLDNAME_LEN_WRITE );
--
--    pszFInfo[11] = psDBF->pachFieldType[iField];
--
--    if( chType == 'C' )
--    {
--        pszFInfo[16] = STATIC_CAST(unsigned char, nWidth % 256);
--        pszFInfo[17] = STATIC_CAST(unsigned char, nWidth / 256);
--    }
--    else
--    {
--        pszFInfo[16] = STATIC_CAST(unsigned char, nWidth);
--        pszFInfo[17] = STATIC_CAST(unsigned char, nDecimals);
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Update offsets                                                  */
--/* -------------------------------------------------------------------- */
--    if (nWidth != nOldWidth)
--    {
--        for (i = iField + 1; i < psDBF->nFields; i++)
--             psDBF->panFieldOffset[i] += nWidth - nOldWidth;
--        psDBF->nRecordLength += nWidth - nOldWidth;
--
--        psDBF->pszCurrentRecord = STATIC_CAST(char *, SfRealloc(psDBF->pszCurrentRecord,
--                                                     psDBF->nRecordLength));
--    }
--
--    /* we're done if we're dealing with not yet created .dbf */
--    if ( psDBF->bNoHeader && psDBF->nRecords == 0 )
--        return TRUE;
--
--    /* force update of header with new header and record length */
--    psDBF->bNoHeader = TRUE;
--    DBFUpdateHeader( psDBF );
--
--    if (nWidth < nOldWidth || (nWidth == nOldWidth && chType != chOldType))
--    {
--        char* pszRecord = STATIC_CAST(char *, malloc(sizeof(char) * nOldRecordLength));
--        char* pszOldField = STATIC_CAST(char *, malloc(sizeof(char) * (nOldWidth + 1)));
--
--        /* cppcheck-suppress uninitdata */
--        pszOldField[nOldWidth] = 0;
--
--        /* move records to their new positions */
--        for (iRecord = 0; iRecord < psDBF->nRecords; iRecord++)
--        {
--            nRecordOffset =
--                nOldRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--            /* load record */
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FRead( pszRecord, nOldRecordLength, 1, psDBF->fp );
--
--            memcpy(pszOldField, pszRecord + nOffset, nOldWidth);
--            bIsNULL = DBFIsValueNULL( chOldType, pszOldField );
--
--            if (nWidth != nOldWidth)
--            {
--                if ((chOldType == 'N' || chOldType == 'F' || chOldType == 'D') && pszOldField[0] == ' ')
--                {
--                    /* Strip leading spaces when truncating a numeric field */
--                    memmove( pszRecord + nOffset,
--                            pszRecord + nOffset + nOldWidth - nWidth,
--                            nWidth );
--                }
--                if (nOffset + nOldWidth < nOldRecordLength)
--                {
--                    memmove( pszRecord + nOffset + nWidth,
--                            pszRecord + nOffset + nOldWidth,
--                            nOldRecordLength - (nOffset + nOldWidth));
--                }
--            }
--
--            /* Convert null value to the appropriate value of the new type */
--            if (bIsNULL)
--            {
--                memset( pszRecord + nOffset, chFieldFill, nWidth);
--            }
--
--            nRecordOffset =
--                psDBF->nRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--            /* write record */
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FWrite( pszRecord, psDBF->nRecordLength, 1, psDBF->fp );
--        }
--
--        if( psDBF->bWriteEndOfFileChar )
--        {
--            char ch = END_OF_FILE_CHARACTER;
--
--            nRecordOffset =
--                psDBF->nRecordLength * STATIC_CAST(SAOffset,psDBF->nRecords) + psDBF->nHeaderLength;
--
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FWrite( &ch, 1, 1, psDBF->fp );
--        }
--        /* TODO: truncate file */
--
--        free(pszRecord);
--        free(pszOldField);
--    }
--    else if (nWidth > nOldWidth)
--    {
--        char* pszRecord = STATIC_CAST(char *, malloc(sizeof(char) * psDBF->nRecordLength));
--        char* pszOldField = STATIC_CAST(char *, malloc(sizeof(char) * (nOldWidth + 1)));
--
--        /* cppcheck-suppress uninitdata */
--        pszOldField[nOldWidth] = 0;
--
--        /* move records to their new positions */
--        for (iRecord = psDBF->nRecords - 1; iRecord >= 0; iRecord--)
--        {
--            nRecordOffset =
--                nOldRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--            /* load record */
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FRead( pszRecord, nOldRecordLength, 1, psDBF->fp );
--
--            memcpy(pszOldField, pszRecord + nOffset, nOldWidth);
--            bIsNULL = DBFIsValueNULL( chOldType, pszOldField );
--
--            if (nOffset + nOldWidth < nOldRecordLength)
--            {
--                memmove( pszRecord + nOffset + nWidth,
--                         pszRecord + nOffset + nOldWidth,
--                         nOldRecordLength - (nOffset + nOldWidth));
--            }
--
--            /* Convert null value to the appropriate value of the new type */
--            if (bIsNULL)
--            {
--                memset( pszRecord + nOffset, chFieldFill, nWidth);
--            }
--            else
--            {
--                if ((chOldType == 'N' || chOldType == 'F'))
--                {
--                    /* Add leading spaces when expanding a numeric field */
--                    memmove( pszRecord + nOffset + nWidth - nOldWidth,
--                             pszRecord + nOffset, nOldWidth );
--                    memset( pszRecord + nOffset, ' ', nWidth - nOldWidth );
--                }
--                else
--                {
--                    /* Add trailing spaces */
--                    memset(pszRecord + nOffset + nOldWidth, ' ', nWidth - nOldWidth);
--                }
--            }
--
--            nRecordOffset =
--                psDBF->nRecordLength * STATIC_CAST(SAOffset,iRecord) + psDBF->nHeaderLength;
--
--            /* write record */
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FWrite( pszRecord, psDBF->nRecordLength, 1, psDBF->fp );
--        }
--
--        if( psDBF->bWriteEndOfFileChar )
--        {
--            char ch = END_OF_FILE_CHARACTER;
--
--            nRecordOffset =
--                psDBF->nRecordLength * STATIC_CAST(SAOffset,psDBF->nRecords) + psDBF->nHeaderLength;
--
--            psDBF->sHooks.FSeek( psDBF->fp, nRecordOffset, 0 );
--            psDBF->sHooks.FWrite( &ch, 1, 1, psDBF->fp );
--        }
--
--        free(pszRecord);
--        free(pszOldField);
--    }
--
--    psDBF->nCurrentRecord = -1;
--    psDBF->bCurrentRecordModified = FALSE;
--    psDBF->bUpdated = TRUE;
--
--    return TRUE;
--}
--
--/************************************************************************/
--/*                    DBFSetWriteEndOfFileChar()                        */
--/************************************************************************/
--
--void SHPAPI_CALL DBFSetWriteEndOfFileChar( DBFHandle psDBF, int bWriteFlag )
--{
--    psDBF->bWriteEndOfFileChar = bWriteFlag;
--}
diff --cc shapelib/safileio.c
index d2c7f581c5a954eff5dd68fff5635851fb88bf5e,d2c7f581c5a954eff5dd68fff5635851fb88bf5e..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,295 -1,295 +1,0 @@@
--/******************************************************************************
-- * $Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $
-- *
-- * Project:  Shapelib
-- * Purpose:  Default implementation of file io based on stdio.
-- * Author:   Frank Warmerdam, warmerdam@pobox.com
-- *
-- ******************************************************************************
-- * Copyright (c) 2007, Frank Warmerdam
-- *
-- * This software is available under the following "MIT Style" license,
-- * or at the option of the licensee under the LGPL (see COPYING).  This
-- * option is discussed in more detail in shapelib.html.
-- *
-- * --
-- * 
-- * Permission is hereby granted, free of charge, to any person obtaining a
-- * copy of this software and associated documentation files (the "Software"),
-- * to deal in the Software without restriction, including without limitation
-- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- * and/or sell copies of the Software, and to permit persons to whom the
-- * Software is furnished to do so, subject to the following conditions:
-- *
-- * The above copyright notice and this permission notice shall be included
-- * in all copies or substantial portions of the Software.
-- *
-- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- * DEALINGS IN THE SOFTWARE.
-- ******************************************************************************
-- *
-- * $Log: safileio.c,v $
-- * Revision 1.6  2018-06-15 19:56:32  erouault
-- * * safileio.c: remove duplicate test. Patch by Jaroslav Fojtik.
-- * Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2744
-- *
-- * Revision 1.5  2016-12-05 12:44:05  erouault
-- * * Major overhaul of Makefile build system to use autoconf/automake.
-- *
-- * * Warning fixes in contrib/
-- *
-- * Revision 1.4  2008-01-16 20:05:14  bram
-- * Add file hooks that accept UTF-8 encoded filenames on some platforms.  Use SASetupUtf8Hooks
-- *  tosetup the hooks and check SHPAPI_UTF8_HOOKS for its availability.  Currently, this
-- *  is only available on the Windows platform that decodes the UTF-8 filenames to wide
-- *  character strings and feeds them to _wfopen and _wremove.
-- *
-- * Revision 1.3  2007/12/18 18:28:11  bram
-- * - create hook for client specific atof (bugzilla ticket 1615)
-- * - check for NULL handle before closing cpCPG file, and close after reading.
-- *
-- * Revision 1.2  2007/12/15 20:25:30  bram
-- * dbfopen.c now reads the Code Page information from the DBF file, and exports
-- * this information as a string through the DBFGetCodePage function.  This is 
-- * either the number from the LDID header field ("LDID/<number>") or as the 
-- * content of an accompanying .CPG file.  When creating a DBF file, the code can
-- * be set using DBFCreateEx.
-- *
-- * Revision 1.1  2007/12/06 06:56:41  fwarmerdam
-- * new
-- *
-- */
--
--#include "shapefil.h"
--
--#include <math.h>
--#include <limits.h>
--#include <assert.h>
--#include <stdlib.h>
--#include <string.h>
--#include <stdio.h>
--
--SHP_CVSID("$Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $");
--
--#ifdef SHPAPI_UTF8_HOOKS
--#   ifdef SHPAPI_WINDOWS
--#       define WIN32_LEAN_AND_MEAN
--#       define NOMINMAX
--#       include <windows.h>
--#       pragma comment(lib, "kernel32.lib")
--#   endif
--#endif
--
--/************************************************************************/
--/*                              SADFOpen()                              */
--/************************************************************************/
--
--SAFile SADFOpen( const char *pszFilename, const char *pszAccess )
--
--{
--    return (SAFile) fopen( pszFilename, pszAccess );
--}
--
--/************************************************************************/
--/*                              SADFRead()                              */
--/************************************************************************/
--
--SAOffset SADFRead( void *p, SAOffset size, SAOffset nmemb, SAFile file )
--
--{
--    return (SAOffset) fread( p, (size_t) size, (size_t) nmemb, 
--                             (FILE *) file );
--}
--
--/************************************************************************/
--/*                             SADFWrite()                              */
--/************************************************************************/
--
--SAOffset SADFWrite( void *p, SAOffset size, SAOffset nmemb, SAFile file )
--
--{
--    return (SAOffset) fwrite( p, (size_t) size, (size_t) nmemb, 
--                              (FILE *) file );
--}
--
--/************************************************************************/
--/*                              SADFSeek()                              */
--/************************************************************************/
--
--SAOffset SADFSeek( SAFile file, SAOffset offset, int whence )
--
--{
--    return (SAOffset) fseek( (FILE *) file, (long) offset, whence );
--}
--
--/************************************************************************/
--/*                              SADFTell()                              */
--/************************************************************************/
--
--SAOffset SADFTell( SAFile file )
--
--{
--    return (SAOffset) ftell( (FILE *) file );
--}
--
--/************************************************************************/
--/*                             SADFFlush()                              */
--/************************************************************************/
--
--int SADFFlush( SAFile file )
--
--{
--    return fflush( (FILE *) file );
--}
--
--/************************************************************************/
--/*                             SADFClose()                              */
--/************************************************************************/
--
--int SADFClose( SAFile file )
--
--{
--    return fclose( (FILE *) file );
--}
--
--/************************************************************************/
--/*                             SADFClose()                              */
--/************************************************************************/
--
--int SADRemove( const char *filename )
--
--{
--    return remove( filename );
--}
--
--/************************************************************************/
--/*                              SADError()                              */
--/************************************************************************/
--
--void SADError( const char *message )
--
--{
--    fprintf( stderr, "%s\n", message );
--}
--
--/************************************************************************/
--/*                        SASetupDefaultHooks()                         */
--/************************************************************************/
--
--void SASetupDefaultHooks( SAHooks *psHooks )
--
--{
--    psHooks->FOpen   = SADFOpen;
--    psHooks->FRead   = SADFRead;
--    psHooks->FWrite  = SADFWrite;
--    psHooks->FSeek   = SADFSeek;
--    psHooks->FTell   = SADFTell;
--    psHooks->FFlush  = SADFFlush;
--    psHooks->FClose  = SADFClose;
--    psHooks->Remove  = SADRemove;
--
--    psHooks->Error   = SADError;
--    psHooks->Atof    = atof;
--}
--
--
--
--
--#ifdef SHPAPI_WINDOWS
--
--/************************************************************************/
--/*                          Utf8ToWideChar                              */
--/************************************************************************/
--
--const wchar_t* Utf8ToWideChar( const char *pszFilename )
--{
--    int nMulti, nWide;
--    wchar_t *pwszFileName;
--    
--    nMulti = strlen(pszFilename) + 1;
--    nWide = MultiByteToWideChar( CP_UTF8, 0, pszFilename, nMulti, 0, 0);
--    if( nWide == 0 )
--    {
--        return NULL;
--    }
--    pwszFileName = (wchar_t*) malloc(nWide * sizeof(wchar_t));
--    if ( pwszFileName == NULL )
--    {
--        return NULL;
--    }
--    if( MultiByteToWideChar( CP_UTF8, 0, pszFilename, nMulti, pwszFileName, nWide ) == 0 )
--    {
--        free( pwszFileName );
--        return NULL;
--    }
--    return pwszFileName;
--}
--
--/************************************************************************/
--/*                           SAUtf8WFOpen                               */
--/************************************************************************/
--
--SAFile SAUtf8WFOpen( const char *pszFilename, const char *pszAccess )
--{
--    SAFile file = NULL;
--    const wchar_t *pwszFileName, *pwszAccess;
--    pwszFileName = Utf8ToWideChar( pszFilename );
--    pwszAccess = Utf8ToWideChar( pszAccess );
--    if( pwszFileName != NULL && pwszAccess != NULL)
--    {
--        file = (SAFile) _wfopen( pwszFileName, pwszAccess );
--    }
--    free ((wchar_t*) pwszFileName);
--    free ((wchar_t*) pwszAccess);
--    return file;
--}
--
--/************************************************************************/
--/*                             SAUtf8WRemove()                          */
--/************************************************************************/
--
--int SAUtf8WRemove( const char *pszFilename )
--{
--    const wchar_t *pwszFileName = Utf8ToWideChar( pszFilename );
--    int rc = -1; 
--    if( pwszFileName != NULL )
--    {
--        rc = _wremove( pwszFileName );
--    }
--    free ((wchar_t*) pwszFileName);
--    return rc;
--}
--
--#endif
--
--#ifdef SHPAPI_UTF8_HOOKS
--
--/************************************************************************/
--/*                          SASetupUtf8Hooks()                          */
--/************************************************************************/
--
--void SASetupUtf8Hooks( SAHooks *psHooks )
--{
--#ifdef SHPAPI_WINDOWS    
--    psHooks->FOpen   = SAUtf8WFOpen;
--    psHooks->Remove  = SAUtf8WRemove;
--#else
--#   error "no implementations of UTF-8 hooks available for this platform"
--#endif
--    psHooks->FRead   = SADFRead;
--    psHooks->FWrite  = SADFWrite;
--    psHooks->FSeek   = SADFSeek;
--    psHooks->FTell   = SADFTell;
--    psHooks->FFlush  = SADFFlush;
--    psHooks->FClose  = SADFClose;
--
--    psHooks->Error   = SADError;
--    psHooks->Atof    = atof;
--}
--
--#endif
diff --cc shapelib/shapefil.h
index 199964d428ede7bf041ec1beb243a1f77fef152f,199964d428ede7bf041ec1beb243a1f77fef152f..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,755 -1,755 +1,0 @@@
--#ifndef SHAPEFILE_H_INCLUDED
--#define SHAPEFILE_H_INCLUDED
--
--/******************************************************************************
-- * $Id: shapefil.h,v 1.56 2018-08-16 15:39:07 erouault Exp $
-- *
-- * Project:  Shapelib
-- * Purpose:  Primary include file for Shapelib.
-- * Author:   Frank Warmerdam, warmerdam@pobox.com
-- *
-- ******************************************************************************
-- * Copyright (c) 1999, Frank Warmerdam
-- * Copyright (c) 2012-2016, Even Rouault <even dot rouault at mines-paris dot org>
-- *
-- * This software is available under the following "MIT Style" license,
-- * or at the option of the licensee under the LGPL (see COPYING).  This
-- * option is discussed in more detail in shapelib.html.
-- *
-- * --
-- *
-- * Permission is hereby granted, free of charge, to any person obtaining a
-- * copy of this software and associated documentation files (the "Software"),
-- * to deal in the Software without restriction, including without limitation
-- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- * and/or sell copies of the Software, and to permit persons to whom the
-- * Software is furnished to do so, subject to the following conditions:
-- *
-- * The above copyright notice and this permission notice shall be included
-- * in all copies or substantial portions of the Software.
-- *
-- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- * DEALINGS IN THE SOFTWARE.
-- ******************************************************************************
-- *
-- * $Log: shapefil.h,v $
-- * Revision 1.56  2018-08-16 15:39:07  erouault
-- * * shpopen.c, dbfopen.c, shptree.c, sbnsearch.c: resyc with GDAL
-- * internal shapelib. Mostly to allow building those files as C++
-- * without warning. Also add FTDate entry in DBFFieldType
-- * (see https://github.com/OSGeo/gdal/pull/308). And some other
-- * code cleanups
-- *
-- * Revision 1.55  2016-12-05 18:44:08  erouault
-- * * dbfopen.c, shapefil.h: write DBF end-of-file character 0x1A by default.
-- * This behaviour can be controlled with the DBFSetWriteEndOfFileChar()
-- * function.
-- *
-- * Revision 1.54  2016-12-05 12:44:05  erouault
-- * * Major overhaul of Makefile build system to use autoconf/automake.
-- *
-- * * Warning fixes in contrib/
-- *
-- * Revision 1.53  2016-12-04 15:30:15  erouault
-- * * shpopen.c, dbfopen.c, shptree.c, shapefil.h: resync with
-- * GDAL Shapefile driver. Mostly cleanups. SHPObject and DBFInfo
-- * structures extended with new members. New functions:
-- * DBFSetLastModifiedDate, SHPOpenLLEx, SHPRestoreSHX,
-- * SHPSetFastModeReadObject
-- *
-- * * sbnsearch.c: new file to implement original ESRI .sbn spatial
-- * index reading. (no write support). New functions:
-- * SBNOpenDiskTree, SBNCloseDiskTree, SBNSearchDiskTree,
-- * SBNSearchDiskTreeInteger, SBNSearchFreeIds
-- *
-- * * Makefile, makefile.vc, CMakeLists.txt, shapelib.def: updates
-- * with new file and symbols.
-- *
-- * * commit: helper script to cvs commit
-- *
-- * Revision 1.52  2011-12-11 22:26:46  fwarmerdam
-- * upgrade .qix access code to use SAHooks (gdal #3365)
-- *
-- * Revision 1.51  2011-07-24 05:59:25  fwarmerdam
-- * minimize use of CPLError in favor of SAHooks.Error()
-- *
-- * Revision 1.50  2011-05-13 17:35:17  fwarmerdam
-- * added DBFReorderFields() and DBFAlterFields() functions (from Even)
-- *
-- * Revision 1.49  2011-04-16 14:38:21  fwarmerdam
-- * avoid warnings with gcc on SHP_CVSID
-- *
-- * Revision 1.48  2010-08-27 23:42:52  fwarmerdam
-- * add SHPAPI_CALL attribute in code
-- *
-- * Revision 1.47  2010-01-28 11:34:34  fwarmerdam
-- * handle the shape file length limits more gracefully (#3236)
-- *
-- * Revision 1.46  2008-11-12 14:28:15  fwarmerdam
-- * DBFCreateField() now works on files with records
-- *
-- * Revision 1.45  2008/11/11 17:47:10  fwarmerdam
-- * added DBFDeleteField() function
-- *
-- * Revision 1.44  2008/01/16 20:05:19  bram
-- * Add file hooks that accept UTF-8 encoded filenames on some platforms.  Use SASetupUtf8Hooks
-- *  tosetup the hooks and check SHPAPI_UTF8_HOOKS for its availability.  Currently, this
-- *  is only available on the Windows platform that decodes the UTF-8 filenames to wide
-- *  character strings and feeds them to _wfopen and _wremove.
-- *
-- * Revision 1.43  2008/01/10 16:35:30  fwarmerdam
-- * avoid _ prefix on #defined symbols (bug 1840)
-- *
-- * Revision 1.42  2007/12/18 18:28:14  bram
-- * - create hook for client specific atof (bugzilla ticket 1615)
-- * - check for NULL handle before closing cpCPG file, and close after reading.
-- *
-- * Revision 1.41  2007/12/15 20:25:32  bram
-- * dbfopen.c now reads the Code Page information from the DBF file, and exports
-- * this information as a string through the DBFGetCodePage function.  This is 
-- * either the number from the LDID header field ("LDID/<number>") or as the 
-- * content of an accompanying .CPG file.  When creating a DBF file, the code can
-- * be set using DBFCreateEx.
-- *
-- * Revision 1.40  2007/12/06 07:00:25  fwarmerdam
-- * dbfopen now using SAHooks for fileio
-- *
-- * Revision 1.39  2007/12/04 20:37:56  fwarmerdam
-- * preliminary implementation of hooks api for io and errors
-- *
-- * Revision 1.38  2007/11/21 22:39:56  fwarmerdam
-- * close shx file in readonly mode (GDAL #1956)
-- *
-- * Revision 1.37  2007/10/27 03:31:14  fwarmerdam
-- * limit default depth of tree to 12 levels (gdal ticket #1594)
-- *
-- * Revision 1.36  2007/09/10 23:33:15  fwarmerdam
-- * Upstreamed support for visibility flag in SHPAPI_CALL for the needs
-- * of GDAL (gdal ticket #1810).
-- *
-- * Revision 1.35  2007/09/03 19:48:10  fwarmerdam
-- * move DBFReadAttribute() static dDoubleField into dbfinfo
-- *
-- * Revision 1.34  2006/06/17 15:33:32  fwarmerdam
-- * added pszWorkField - bug 1202 (rso)
-- *
-- * Revision 1.33  2006/02/15 01:14:30  fwarmerdam
-- * added DBFAddNativeFieldType
-- *
-- * Revision 1.32  2006/01/26 15:07:32  fwarmerdam
-- * add bMeasureIsUsed flag from Craig Bruce: Bug 1249
-- *
-- * Revision 1.31  2006/01/05 01:27:27  fwarmerdam
-- * added dbf deletion mark/fetch
-- *
-- * Revision 1.30  2005/01/03 22:30:13  fwarmerdam
-- * added support for saved quadtrees
-- *
-- * Revision 1.29  2004/09/26 20:09:35  fwarmerdam
-- * avoid rcsid warnings
-- *
-- * Revision 1.28  2003/12/29 06:02:18  fwarmerdam
-- * added cpl_error.h option
-- *
-- * Revision 1.27  2003/04/21 18:30:37  warmerda
-- * added header write/update public methods
-- *
-- * Revision 1.26  2002/09/29 00:00:08  warmerda
-- * added FTLogical and logical attribute read/write calls
-- *
-- * Revision 1.25  2002/05/07 13:46:30  warmerda
-- * added DBFWriteAttributeDirectly().
-- *
-- * Revision 1.24  2002/04/10 16:59:54  warmerda
-- * added SHPRewindObject
-- *
-- * Revision 1.23  2002/01/15 14:36:07  warmerda
-- * updated email address
-- *
-- * Revision 1.22  2002/01/15 14:32:00  warmerda
-- * try to improve SHPAPI_CALL docs
-- */
--
--#include <stdio.h>
--
--#ifdef USE_DBMALLOC
--#include <dbmalloc.h>
--#endif
--
--#ifdef USE_CPL
--#include "cpl_conv.h"
--#endif
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--/************************************************************************/
--/*                        Configuration options.                        */
--/************************************************************************/
--
--/* -------------------------------------------------------------------- */
--/*      Should the DBFReadStringAttribute() strip leading and           */
--/*      trailing white space?                                           */
--/* -------------------------------------------------------------------- */
--#define TRIM_DBF_WHITESPACE
--
--/* -------------------------------------------------------------------- */
--/*      Should we write measure values to the Multipatch object?        */
--/*      Reportedly ArcView crashes if we do write it, so for now it     */
--/*      is disabled.                                                    */
--/* -------------------------------------------------------------------- */
--#define DISABLE_MULTIPATCH_MEASURE
--
--/* -------------------------------------------------------------------- */
--/*      SHPAPI_CALL                                                     */
--/*                                                                      */
--/*      The following two macros are present to allow forcing           */
--/*      various calling conventions on the Shapelib API.                */
--/*                                                                      */
--/*      To force __stdcall conventions (needed to call Shapelib         */
--/*      from Visual Basic and/or Dephi I believe) the makefile could    */
--/*      be modified to define:                                          */
--/*                                                                      */
--/*        /DSHPAPI_CALL=__stdcall                                       */
--/*                                                                      */
--/*      If it is desired to force export of the Shapelib API without    */
--/*      using the shapelib.def file, use the following definition.      */
--/*                                                                      */
--/*        /DSHAPELIB_DLLEXPORT                                          */
--/*                                                                      */
--/*      To get both at once it will be necessary to hack this           */
--/*      include file to define:                                         */
--/*                                                                      */
--/*        #define SHPAPI_CALL __declspec(dllexport) __stdcall           */
--/*        #define SHPAPI_CALL1 __declspec(dllexport) * __stdcall        */
--/*                                                                      */
--/*      The complexity of the situation is partly caused by the        */
--/*      peculiar requirement of Visual C++ that __stdcall appear        */
--/*      after any "*"'s in the return value of a function while the     */
--/*      __declspec(dllexport) must appear before them.                  */
--/* -------------------------------------------------------------------- */
--
--#ifdef SHAPELIB_DLLEXPORT
--#  define SHPAPI_CALL __declspec(dllexport)
--#  define SHPAPI_CALL1(x)  __declspec(dllexport) x
--#endif
--
--#ifndef SHPAPI_CALL
--#  if defined(USE_GCC_VISIBILITY_FLAG)
--#    define SHPAPI_CALL     __attribute__ ((visibility("default")))
--#    define SHPAPI_CALL1(x) __attribute__ ((visibility("default")))     x
--#  else
--#    define SHPAPI_CALL
--#  endif
--#endif
--
--#ifndef SHPAPI_CALL1
--#  define SHPAPI_CALL1(x)      x SHPAPI_CALL
--#endif
--
--/* -------------------------------------------------------------------- */
--/*      Macros for controlling CVSID and ensuring they don't appear     */
--/*      as unreferenced variables resulting in lots of warnings.        */
--/* -------------------------------------------------------------------- */
--#ifndef DISABLE_CVSID
--#  if defined(__GNUC__) && __GNUC__ >= 4
--#    define SHP_CVSID(string)     static const char cpl_cvsid[] __attribute__((used)) = string;
--#  else
--#    define SHP_CVSID(string)     static const char cpl_cvsid[] = string; \
--static const char *cvsid_aw() { return( cvsid_aw() ? NULL : cpl_cvsid ); }
--#  endif
--#else
--#  define SHP_CVSID(string)
--#endif
--
--/* -------------------------------------------------------------------- */
--/*      On some platforms, additional file IO hooks are defined that    */
--/*      UTF-8 encoded filenames Unicode filenames                       */
--/* -------------------------------------------------------------------- */
--#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
--#  define SHPAPI_WINDOWS
--#  define SHPAPI_UTF8_HOOKS
--#endif
--
--/* -------------------------------------------------------------------- */
--/*      IO/Error hook functions.                                        */
--/* -------------------------------------------------------------------- */
--typedef int *SAFile;
--
--#ifndef SAOffset
--typedef unsigned long SAOffset;
--#endif
--
--typedef struct {
--    SAFile     (*FOpen) ( const char *filename, const char *access);
--    SAOffset   (*FRead) ( void *p, SAOffset size, SAOffset nmemb, SAFile file);
--    SAOffset   (*FWrite)( void *p, SAOffset size, SAOffset nmemb, SAFile file);
--    SAOffset   (*FSeek) ( SAFile file, SAOffset offset, int whence );
--    SAOffset   (*FTell) ( SAFile file );
--    int        (*FFlush)( SAFile file );
--    int        (*FClose)( SAFile file );
--    int        (*Remove) ( const char *filename );
--
--    void       (*Error) ( const char *message );
--    double     (*Atof)  ( const char *str );
--} SAHooks;
--
--void SHPAPI_CALL SASetupDefaultHooks( SAHooks *psHooks );
--#ifdef SHPAPI_UTF8_HOOKS
--void SHPAPI_CALL SASetupUtf8Hooks( SAHooks *psHooks );
--#endif
--
--/************************************************************************/
--/*                             SHP Support.                             */
--/************************************************************************/
--typedef struct tagSHPObject SHPObject;
--
--typedef struct
--{
--    SAHooks sHooks;
--
--    SAFile      fpSHP;
--    SAFile      fpSHX;
--
--    int         nShapeType;  /* SHPT_* */
--
--    unsigned int nFileSize;  /* SHP file */
--
--    int         nRecords;
--    int         nMaxRecords;
--    unsigned int*panRecOffset;
--    unsigned int *panRecSize;
--
--    double      adBoundsMin[4];
--    double      adBoundsMax[4];
--
--    int         bUpdated;
--
--    unsigned char *pabyRec;
--    int         nBufSize;
--
--    int            bFastModeReadObject;
--    unsigned char *pabyObjectBuf;
--    int            nObjectBufSize;
--    SHPObject*     psCachedObject;
--} SHPInfo;
--
--typedef SHPInfo * SHPHandle;
--
--/* -------------------------------------------------------------------- */
--/*      Shape types (nSHPType)                                          */
--/* -------------------------------------------------------------------- */
--#define SHPT_NULL       0
--#define SHPT_POINT      1
--#define SHPT_ARC        3
--#define SHPT_POLYGON    5
--#define SHPT_MULTIPOINT 8
--#define SHPT_POINTZ     11
--#define SHPT_ARCZ       13
--#define SHPT_POLYGONZ   15
--#define SHPT_MULTIPOINTZ 18
--#define SHPT_POINTM     21
--#define SHPT_ARCM       23
--#define SHPT_POLYGONM   25
--#define SHPT_MULTIPOINTM 28
--#define SHPT_MULTIPATCH 31
--
--/* -------------------------------------------------------------------- */
--/*      Part types - everything but SHPT_MULTIPATCH just uses           */
--/*      SHPP_RING.                                                      */
--/* -------------------------------------------------------------------- */
--
--#define SHPP_TRISTRIP   0
--#define SHPP_TRIFAN     1
--#define SHPP_OUTERRING  2
--#define SHPP_INNERRING  3
--#define SHPP_FIRSTRING  4
--#define SHPP_RING       5
--
--/* -------------------------------------------------------------------- */
--/*      SHPObject - represents on shape (without attributes) read       */
--/*      from the .shp file.                                             */
--/* -------------------------------------------------------------------- */
--struct tagSHPObject
--{
--    int    nSHPType;
--
--    int    nShapeId;  /* -1 is unknown/unassigned */
--
--    int    nParts;
--    int    *panPartStart;
--    int    *panPartType;
--
--    int    nVertices;
--    double *padfX;
--    double *padfY;
--    double *padfZ;
--    double *padfM;
--
--    double dfXMin;
--    double dfYMin;
--    double dfZMin;
--    double dfMMin;
--
--    double dfXMax;
--    double dfYMax;
--    double dfZMax;
--    double dfMMax;
--
--    int    bMeasureIsUsed;
--    int    bFastModeReadObject;
--};
--
--/* -------------------------------------------------------------------- */
--/*      SHP API Prototypes                                              */
--/* -------------------------------------------------------------------- */
--
--/* If pszAccess is read-only, the fpSHX field of the returned structure */
--/* will be NULL as it is not necessary to keep the SHX file open */
--SHPHandle SHPAPI_CALL
--      SHPOpen( const char * pszShapeFile, const char * pszAccess );
--SHPHandle SHPAPI_CALL
--      SHPOpenLL( const char *pszShapeFile, const char *pszAccess,
--                 SAHooks *psHooks );
--SHPHandle SHPAPI_CALL
--      SHPOpenLLEx( const char *pszShapeFile, const char *pszAccess,
--                  SAHooks *psHooks, int bRestoreSHX );
--
--int SHPAPI_CALL
--      SHPRestoreSHX( const char *pszShapeFile, const char *pszAccess,
--                  SAHooks *psHooks );
--
--/* If setting bFastMode = TRUE, the content of SHPReadObject() is owned by the SHPHandle. */
--/* So you cannot have 2 valid instances of SHPReadObject() simultaneously. */
--/* The SHPObject padfZ and padfM members may be NULL depending on the geometry */
--/* type. It is illegal to free at hand any of the pointer members of the SHPObject structure */
--void SHPAPI_CALL SHPSetFastModeReadObject( SHPHandle hSHP, int bFastMode );
--
--SHPHandle SHPAPI_CALL
--      SHPCreate( const char * pszShapeFile, int nShapeType );
--SHPHandle SHPAPI_CALL
--      SHPCreateLL( const char * pszShapeFile, int nShapeType,
--                   SAHooks *psHooks );
--void SHPAPI_CALL
--      SHPGetInfo( SHPHandle hSHP, int * pnEntities, int * pnShapeType,
--                  double * padfMinBound, double * padfMaxBound );
--
--SHPObject SHPAPI_CALL1(*)
--      SHPReadObject( SHPHandle hSHP, int iShape );
--int SHPAPI_CALL
--      SHPWriteObject( SHPHandle hSHP, int iShape, SHPObject * psObject );
--
--void SHPAPI_CALL
--      SHPDestroyObject( SHPObject * psObject );
--void SHPAPI_CALL
--      SHPComputeExtents( SHPObject * psObject );
--SHPObject SHPAPI_CALL1(*)
--      SHPCreateObject( int nSHPType, int nShapeId, int nParts,
--                       const int * panPartStart, const int * panPartType,
--                       int nVertices,
--                       const double * padfX, const double * padfY,
--                       const double * padfZ, const double * padfM );
--SHPObject SHPAPI_CALL1(*)
--      SHPCreateSimpleObject( int nSHPType, int nVertices,
--                             const double * padfX,
--                             const double * padfY,
--                             const double * padfZ );
--
--int SHPAPI_CALL
--      SHPRewindObject( SHPHandle hSHP, SHPObject * psObject );
--
--void SHPAPI_CALL SHPClose( SHPHandle hSHP );
--void SHPAPI_CALL SHPWriteHeader( SHPHandle hSHP );
--
--const char SHPAPI_CALL1(*)
--      SHPTypeName( int nSHPType );
--const char SHPAPI_CALL1(*)
--      SHPPartTypeName( int nPartType );
--
--/* -------------------------------------------------------------------- */
--/*      Shape quadtree indexing API.                                    */
--/* -------------------------------------------------------------------- */
--
--/* this can be two or four for binary or quad tree */
--#define MAX_SUBNODE 4
--
--/* upper limit of tree levels for automatic estimation */
--#define MAX_DEFAULT_TREE_DEPTH 12
--
--typedef struct shape_tree_node
--{
--    /* region covered by this node */
--    double      adfBoundsMin[4];
--    double      adfBoundsMax[4];
--
--    /* list of shapes stored at this node.  The papsShapeObj pointers
--       or the whole list can be NULL */
--    int         nShapeCount;
--    int         *panShapeIds;
--    SHPObject   **papsShapeObj;
--
--    int         nSubNodes;
--    struct shape_tree_node *apsSubNode[MAX_SUBNODE];
--
--} SHPTreeNode;
--
--typedef struct
--{
--    SHPHandle   hSHP;
--
--    int         nMaxDepth;
--    int         nDimension;
--    int         nTotalCount;
--
--    SHPTreeNode *psRoot;
--} SHPTree;
--
--SHPTree SHPAPI_CALL1(*)
--      SHPCreateTree( SHPHandle hSHP, int nDimension, int nMaxDepth,
--                     double *padfBoundsMin, double *padfBoundsMax );
--void SHPAPI_CALL
--      SHPDestroyTree( SHPTree * hTree );
--
--int SHPAPI_CALL
--      SHPWriteTree( SHPTree *hTree, const char * pszFilename );
--
--int SHPAPI_CALL
--      SHPTreeAddShapeId( SHPTree * hTree, SHPObject * psObject );
--int SHPAPI_CALL
--      SHPTreeRemoveShapeId( SHPTree * hTree, int nShapeId );
--
--void SHPAPI_CALL
--      SHPTreeTrimExtraNodes( SHPTree * hTree );
--
--int SHPAPI_CALL1(*)
--      SHPTreeFindLikelyShapes( SHPTree * hTree,
--                               double * padfBoundsMin,
--                               double * padfBoundsMax,
--                               int * );
--int SHPAPI_CALL
--      SHPCheckBoundsOverlap( double *, double *, double *, double *, int );
--
--int SHPAPI_CALL1(*)
--SHPSearchDiskTree( FILE *fp,
--                   double *padfBoundsMin, double *padfBoundsMax,
--                   int *pnShapeCount );
--
--typedef struct SHPDiskTreeInfo* SHPTreeDiskHandle;
--
--SHPTreeDiskHandle SHPAPI_CALL
--    SHPOpenDiskTree( const char* pszQIXFilename,
--                     SAHooks *psHooks );
--
--void SHPAPI_CALL
--    SHPCloseDiskTree( SHPTreeDiskHandle hDiskTree );
--
--int SHPAPI_CALL1(*)
--SHPSearchDiskTreeEx( SHPTreeDiskHandle hDiskTree,
--                     double *padfBoundsMin, double *padfBoundsMax,
--                     int *pnShapeCount );
--
--int SHPAPI_CALL
--    SHPWriteTreeLL(SHPTree *hTree, const char *pszFilename, SAHooks *psHooks );
--
--/* -------------------------------------------------------------------- */
--/*      SBN Search API                                                  */
--/* -------------------------------------------------------------------- */
--
--typedef struct SBNSearchInfo* SBNSearchHandle;
--
--SBNSearchHandle SHPAPI_CALL
--    SBNOpenDiskTree( const char* pszSBNFilename,
--                 SAHooks *psHooks );
--
--void SHPAPI_CALL
--    SBNCloseDiskTree( SBNSearchHandle hSBN );
--
--int SHPAPI_CALL1(*)
--SBNSearchDiskTree( SBNSearchHandle hSBN,
--                   double *padfBoundsMin, double *padfBoundsMax,
--                   int *pnShapeCount );
--
--int SHPAPI_CALL1(*)
--SBNSearchDiskTreeInteger( SBNSearchHandle hSBN,
--                          int bMinX, int bMinY, int bMaxX, int bMaxY,
--                          int *pnShapeCount );
--
--void SHPAPI_CALL SBNSearchFreeIds( int* panShapeId );
--
--/************************************************************************/
--/*                             DBF Support.                             */
--/************************************************************************/
--typedef struct
--{
--    SAHooks sHooks;
--
--    SAFile      fp;
--
--    int         nRecords;
--
--    int         nRecordLength; /* Must fit on uint16 */
--    int         nHeaderLength; /* File header length (32) + field
--                                  descriptor length + spare space.
--                                  Must fit on uint16 */
--    int         nFields;
--    int         *panFieldOffset;
--    int         *panFieldSize;
--    int         *panFieldDecimals;
--    char        *pachFieldType;
--
--    char        *pszHeader; /* Field descriptors */
--
--    int         nCurrentRecord;
--    int         bCurrentRecordModified;
--    char        *pszCurrentRecord;
--
--    int         nWorkFieldLength;
--    char        *pszWorkField;
--
--    int         bNoHeader;
--    int         bUpdated;
--
--    union
--    {
--        double      dfDoubleField;
--        int         nIntField;
--    } fieldValue;
--
--    int         iLanguageDriver;
--    char        *pszCodePage;
--
--    int         nUpdateYearSince1900; /* 0-255 */
--    int         nUpdateMonth; /* 1-12 */
--    int         nUpdateDay; /* 1-31 */
--
--    int         bWriteEndOfFileChar; /* defaults to TRUE */
--} DBFInfo;
--
--typedef DBFInfo * DBFHandle;
--
--typedef enum {
--  FTString,
--  FTInteger,
--  FTDouble,
--  FTLogical,
--  FTDate,
--  FTInvalid
--} DBFFieldType;
--
--/* Field descriptor/header size */
--#define XBASE_FLDHDR_SZ         32
--/* Shapelib read up to 11 characters, even if only 10 should normally be used */
--#define XBASE_FLDNAME_LEN_READ  11
--/* On writing, we limit to 10 characters */
--#define XBASE_FLDNAME_LEN_WRITE 10
--/* Normally only 254 characters should be used. We tolerate 255 historically */
--#define XBASE_FLD_MAX_WIDTH     255
--
--DBFHandle SHPAPI_CALL
--      DBFOpen( const char * pszDBFFile, const char * pszAccess );
--DBFHandle SHPAPI_CALL
--      DBFOpenLL( const char * pszDBFFile, const char * pszAccess,
--                 SAHooks *psHooks );
--DBFHandle SHPAPI_CALL
--      DBFCreate( const char * pszDBFFile );
--DBFHandle SHPAPI_CALL
--      DBFCreateEx( const char * pszDBFFile, const char * pszCodePage );
--DBFHandle SHPAPI_CALL
--      DBFCreateLL( const char * pszDBFFile, const char * pszCodePage, SAHooks *psHooks );
--
--int SHPAPI_CALL
--      DBFGetFieldCount( DBFHandle psDBF );
--int SHPAPI_CALL
--      DBFGetRecordCount( DBFHandle psDBF );
--int SHPAPI_CALL
--      DBFAddField( DBFHandle hDBF, const char * pszFieldName,
--                   DBFFieldType eType, int nWidth, int nDecimals );
--
--int SHPAPI_CALL
--      DBFAddNativeFieldType( DBFHandle hDBF, const char * pszFieldName,
--                             char chType, int nWidth, int nDecimals );
--
--int SHPAPI_CALL
--      DBFDeleteField( DBFHandle hDBF, int iField );
--
--int SHPAPI_CALL
--      DBFReorderFields( DBFHandle psDBF, int* panMap );
--
--int SHPAPI_CALL
--      DBFAlterFieldDefn( DBFHandle psDBF, int iField, const char * pszFieldName,
--                         char chType, int nWidth, int nDecimals );
--
--DBFFieldType SHPAPI_CALL
--      DBFGetFieldInfo( DBFHandle psDBF, int iField,
--                       char * pszFieldName, int * pnWidth, int * pnDecimals );
--
--int SHPAPI_CALL
--      DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName);
--
--int SHPAPI_CALL
--      DBFReadIntegerAttribute( DBFHandle hDBF, int iShape, int iField );
--double SHPAPI_CALL
--      DBFReadDoubleAttribute( DBFHandle hDBF, int iShape, int iField );
--const char SHPAPI_CALL1(*)
--      DBFReadStringAttribute( DBFHandle hDBF, int iShape, int iField );
--const char SHPAPI_CALL1(*)
--      DBFReadLogicalAttribute( DBFHandle hDBF, int iShape, int iField );
--int SHPAPI_CALL
--      DBFIsAttributeNULL( DBFHandle hDBF, int iShape, int iField );
--
--int SHPAPI_CALL
--      DBFWriteIntegerAttribute( DBFHandle hDBF, int iShape, int iField,
--                                int nFieldValue );
--int SHPAPI_CALL
--      DBFWriteDoubleAttribute( DBFHandle hDBF, int iShape, int iField,
--                               double dFieldValue );
--int SHPAPI_CALL
--      DBFWriteStringAttribute( DBFHandle hDBF, int iShape, int iField,
--                               const char * pszFieldValue );
--int SHPAPI_CALL
--     DBFWriteNULLAttribute( DBFHandle hDBF, int iShape, int iField );
--
--int SHPAPI_CALL
--     DBFWriteLogicalAttribute( DBFHandle hDBF, int iShape, int iField,
--                               const char lFieldValue);
--int SHPAPI_CALL
--     DBFWriteAttributeDirectly(DBFHandle psDBF, int hEntity, int iField,
--                               void * pValue );
--const char SHPAPI_CALL1(*)
--      DBFReadTuple(DBFHandle psDBF, int hEntity );
--int SHPAPI_CALL
--      DBFWriteTuple(DBFHandle psDBF, int hEntity, void * pRawTuple );
--
--int SHPAPI_CALL DBFIsRecordDeleted( DBFHandle psDBF, int iShape );
--int SHPAPI_CALL DBFMarkRecordDeleted( DBFHandle psDBF, int iShape,
--                                      int bIsDeleted );
--
--DBFHandle SHPAPI_CALL
--      DBFCloneEmpty(DBFHandle psDBF, const char * pszFilename );
--
--void SHPAPI_CALL
--      DBFClose( DBFHandle hDBF );
--void    SHPAPI_CALL
--      DBFUpdateHeader( DBFHandle hDBF );
--char SHPAPI_CALL
--      DBFGetNativeFieldType( DBFHandle hDBF, int iField );
--
--const char SHPAPI_CALL1(*)
--      DBFGetCodePage(DBFHandle psDBF );
--
--void SHPAPI_CALL
--    DBFSetLastModifiedDate( DBFHandle psDBF, int nYYSince1900, int nMM, int nDD );
--
--void SHPAPI_CALL DBFSetWriteEndOfFileChar( DBFHandle psDBF, int bWriteFlag );
--
--#ifdef __cplusplus
--}
--#endif
--
--#endif /* ndef SHAPEFILE_H_INCLUDED */
diff --cc shapelib/shapelib.html
index fa81f91aa6aefdf76b0b945aaf3b54146c10a368,fa81f91aa6aefdf76b0b945aaf3b54146c10a368..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,231 -1,231 +1,0 @@@
--<html>
--<head>
--<title>Shapefile C Library</title>
--<link href="maptools.css" rel="stylesheet" type="text/css">
--</head>
--
--<body>
--<h1>Shapefile C Library</h1>
--
--<h2>Purpose</h2>
--
--The Shapefile C Library provides the ability to write simple C programs
--for reading, writing and updating (to a limited extent) ESRI Shapefiles,
--and the associated attribute file (.dbf).<p>
--
--<h2>Supporting Information</h2>
--
--<ul>
--<li> <a href="shp_api.html">Shapefile API Docs</a>
--<li> <a href="dbf_api.html">DBF/xBase API Docs</a>
--<li> <a href="shapelib-tools.html">Shapefile Tools Docs</a>
--<li> <a href="release.html">Release Notes</a>
--<li> <a href="manifest.html">Shapelib File Manifest</a>
--<li> <a href="license.html">Shapelib Licensing Terms</a>
--</ul>
--
--<h2>What is a Shapefile?</h2>
--
--If you don't know, you probably don't need this library.  The Shapefile
--format is a working and interchange format promulagated by 
--<a href="http://www.esri.com/">ESRI</a> for simple vector data with attributes.
--<p>
--
--An excellent <a href="dl/shapefile.pdf">white paper</a> on the shapefile format 
--is available from ESRI,
--but it is .pdf format, so you will need Adobe Acrobat to browse it.<p>
--
--The file format actually consists of three files.<p>
--
--<pre>
--XXX.shp - holds the actual vertices.
--XXX.shx - hold index data pointing to the structures in the .shp file.
--XXX.dbf - holds the attributes in xBase (dBase) format.  
--</pre>
--
--<h2>Download</h2>
--
--Source code, and some other odds and ends can be downloaded from
--<a href="http://download.osgeo.org/shapelib">http://download.osgeo.org/shapelib</a>.<p>
--
--Shapelib is available for anonymous CVS access:
--
--<pre>
--  cvs -d :pserver:cvsanon@cvs.maptools.org:/cvs/maptools/cvsroot login
--  Password: (hit enter)
--  cvs -d :pserver:cvsanon@cvs.maptools.org:/cvs/maptools/cvsroot co shapelib
--</pre>
--
--<h2>Bugs, Maintainance and Support</h2>
--
--This library is maintained by <a href="http://pobox.com/~warmerdam">Frank 
--Warmerdam</a>.  Please send me bug reports, patches and suggestions for the 
--library via the <a href="http://bugzilla.maptools.org/enter_bug.cgi?product=Shapelib">maptools.org Bugzilla</a>.  Shapelib bugs can also be
--<a href="http://bugzilla.maptools.org/query.cgi?product=Shapelib">queried</a>.
--<p>
--
--Shapelib is hosted at 
--<a href="http://shapelib.maptools.org">shapelib.maptools.org</a>.   A mailing
--list for discussion of how to use shapelib, and announcing new releases 
--<a href="http://lists.maptools.org/mailman/listinfo/shapelib/">is 
--available</a>. To get notification of new releases of Shapelib <i>subscribe</i> to 
--the project mailing list at https://lists.osgeo.org/pipermail/shapelib/.<p>
--
--<h2>Credits</h2>
--
--I didn't start this section anywhere near soon enough, so alot of earlier
--contributors to Shapelib are lost in pre-history.
--
--<ul>
--<li> Bill Miller (NY-DOT) for shputils.c
--<li> Carl Anderson for the contents of the contrib directory, and 
--the "tuple" additions to dbfopen.c.
--<li> Andrea Giacomelli for patches for dbfopen.c.
--<li> Doug Matthews for portability improvements.
--<li> Jan-Oliver Wagner for convincing me to make it available under LGPL,
--shared library support, and various other patches.
--<li> Dennis Christopher (of Avenza) for testing and bug fixes.
--<li> Miko Syrjä (of 3D-system Oy) for a record size bug fix.
--<li> Steven Lime and Curtis Hill for help with NULL shapes.
--<li> Jim Matthews for support of NULL attributes in dbf files.
--<li> <a href="http://www.pcigeomatics.com/">PCI Geomatics</a> who let me
--release a modified version of their shapefile code in the beginning and
--who hosted shapelib for years.
--</ul>
--
--<h2>In Memorium</h2>
--
--I would like to dedicate Shapelib to the memory of Sol Katz.  While I never
--met him in person, his generous contributions to the GIS community took 
--many forms, including free distribution of a variety of GIS translators
--with source.  The fact that he used this Shapelib in some of his utilities, 
--and thanked me was a great encouragement to me.  I hope I can do his memory 
--honour by trying to contribute in a similar fashion.<p>
--
--<h2>Portability</h2>
--
--The Shapefile C Library should port easily to 32bit systems with ANSI C
--compilers.  It should work on 64 bit architectures (such as the DEC AXP).<p>
--
--Care should also be taken to pass the binary access flag into SHPOpen()
--and DBFOpen() when operating on systems with special text file translation
--such as MSDOS.<p>
--
--The shputils.c module is contributed, and may not take the same approach
--to portability as the rest of the package.<p>
--
--On Linux, and most unix systems it should be possible to build and 
--install shapefile support as a shared library using the "lib" and "lib_install"
--targets of the Makefile.  Note that this Makefile doesn't use autoconf
--mechanisms and will generally require some hand tailoring for your environment.
--
--<h2>Limitations</h2>
--
--<ul>
--
--<li> You can't modify the vertices of existing structures (though you 
--   can update the attributes of existing structures, and create new 
--   structures).<p>
--
--<li> Not written in such a way as to be particularly fast.  This is 
--particularly true of the 1.2 API.  For applications more concerned with
--speed it may be worth using the V1.1 API.<p>
--
--<li> Doesn't set the last access time properly in the .dbf files.<p>
--
--<li> There is no way to synchronize information to the file except to close it.
--<p>
--
--<li> Poor error checking and reporting.<p>
--
--<li> Not professionally supported (well it can be, if you want to pay).<p>
--
--<li> Some aspects of xBase files not supported, though I believe they are
--not used by ESRI.<p>
--
--<li> The application must keep the .dbf file in sync with the .shp/.shx
--files through appropriate use of the DBF and SHP APIs.<p>
--
--<li> No support for the undocumented .sbn/.sbx spatial index files.<p>
--
--</ul>
--
--<h2>Other Shapefile Resources</h2>
--
--<ul>
--<li> <a href="dl/shapefile.pdf">Shapefile Format Specifications (pdf)</a><p>
--
--<li> <a href="http://www.clicketyclick.dk/databases/xbase/format/">Xbase (.dbf) File Format Description</a>. <p>
--
--<li> <a href="codepage.html">Language ID / Code Page mappings</a><p>
--
--<li> Shapelib is used within the multiformat 
--<a href="http://ogr.maptools.org/">OGR</a> library.  If you are looking for a 
--high level C++ library with support for many geospatial vector formats you
--might want to check it out.<p>
--
--<li> Ari Jolma has produced an initial <b>perl</b> binding on top of shapelib, 
--which can be found at CPAN as Geo::ShapeFile under the 
--<a href="http://www.cpan.org/modules/by-module/Geo/">Geo</a> module.
--<p>
--
--<li> Bernhard Herzog has produced <b>python</b> bindings for Shapelib with 
--SWIG, available at <a href="http://ftp.intevation.de/users/bh/pyshapelib/">http://ftp.intevation.de/users/bh/pyshapelib</a>.  A new version not using swig is 
--available as <a href="http://wald.intevation.org/plugins/scmsvn/viewcvs.php/trunk/thuban/libraries/pyshapelib/?root=thuban">part of Thuban</a>.<p>
--
--<li> <a href="http://www.triplexware.huckfinn.de/shpapi.html">Delphi</a>
--bindings for Shapelib courtesy of Alexander Weidauer.<p>
--
--<li> Miguel Filgueiras has implemented 
--<a href="http://www.ncc.up.pt/gpsmanshp/">Tcl</a> bindings for Shapelib
--as part of <a href="http://www.ncc.up.pt/gpsman/">GPSMan</a>.<p>
--
--<li> David Gancarz has implemented a Microsoft
--<a href="dl/contrib/DotNetArchive.zip">.NET wrapper</a> for
--Shapelib.   An example of using shapelib with VB6 is also icluded in the .NET wrapper project file.<p>
--
--<li> Andrey Hristov (php at hristov dot com) has developed a PHP extension 
--based on Shapelib.  It can be found in CVS at http://cvs.php.net/pecl/shp.<p>
--
--<li> Toyoda Eizi has developed Ruby bindings found at
--<a href="http://sourceforge.net/projects/ruby-shapelib">http://sourceforge.net/projects/ruby-shapelib</a>.<p>
--
--<li> Davide Cesari has developed FORTRAN bindings that can be found at
--<a href"http://www.webalice.it/o.drofa/davide/shapelib-fortran/">
--http://www.webalice.it/o.drofa/davide/shapelib-fortran</a>.
--
--<li> Jan-Oliver Wagner has implemented a commandline program
--(<b>gen2shp</b>) for producing shapefiles from Arc/Info Generate format ASCII
--files.  He maintains a <a href="http://intevation.de/~jan/gen2shp">web page</a> for his work. <p>
--
--<li> Tom Russo has implemented a shpcs2cs program, which reprojects shapefiles
--using arguments similar to the PROJ.4 cs2cs program including datum conversion.
--Use as an alternate to the contrib/shpproj which doesn't do datums.  It is 
--available at the bottom of Tom's <a href="http://www.swcp.com/~russo/shape_web/">Xastir Shapefile Resources</a> page. <p>
--
--<li> 
--Andrew Williamson's 
--<a href="http://www.geocities.com/SiliconValley/Haven/2295/useful.html">Useful
--Scripts and Stuff</a> page for ArcView, which includes ShapeChecker.<p>
--
--<li> The University of Bonn <a href="http://katla.giub.uni-bonn.de/sfjava/">
--sf4java</a> project apparently includes Java classes for reading Shapefiles.<p>
--
--<li> The <a href="http://gis.esri.com/arcscripts/details.cfm?CFGRIDKEY=628102085">ShapeIO2</a> Visual Basic libraries may be of interest to those wanting
--VB access to Shapefiles.  Also available <a href="http://shapelib.maptools.org/dl/contrib/ShapeIO2.zip">locally</a>.<p>
--
--<li> The <a href="http://arcscripts.esri.com/details.asp?dbid=11810">ShapeFile Read/Write OCX</a> is another option for Visual Basic programmers.<p>
--
--<li> <a href="http://www.casa.ucl.ac.uk/sanjay/software_isovistanalyst.htm">Isovist Analyst</a> is a sort-of-free isovist generating extension for 
--ArcView using shapelib.<p>
--
--<li> <a href="http://www.obviously.com/gis/shpdiff/">shpdiff</a> utility 
--by Bryce Nesbitt.<p>
--
--<li> <a href="http://www.aequometer.de/">Aequometer</a>: a program for 
--MS Excel to calculate the area of polygons and export as shapefiles.<p>
--
--</ul>
--
--</body>
--</html>
diff --cc shapelib/shp_api.html
index d773e3e56867e091437f1613926552a9622d8432,d773e3e56867e091437f1613926552a9622d8432..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,376 -1,376 +1,0 @@@
--<html>
--<head>
--<title>.SHP File API</title>
--</head>
--<body>
--
--<h1>.SHP File API</h1>
--
--The .SHP API uses a SHPHandle to represent an open .shp/.shx file pair.
--The contents of the SHPHandle are visible (see shapefile.h) but should
--be ignored by the application.  It is intended that all information be
--accessed by the API functions.  <p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>Shape Types</h2>
--
--Shapes have types associated with them.  The following is a list of the
--different shapetypes supported by Shapefiles.  At this time all shapes in
--a Shapefile must be of the same type (with the exception of NULL shapes). <p>
--
--<pre>
--  #define SHPT_NULL             0
--
--  2D Shape Types (pre ArcView 3.x):
--
--  #define SHPT_POINT          1       Points
--  #define SHPT_ARC            3       Arcs (Polylines, possible in parts)
--  #define SHPT_POLYGON                5       Polygons (possible in parts)
--  #define SHPT_MULTIPOINT     8       MultiPoint (related points)
--
--  3D Shape Types (may include "measure" values for vertices):
--
--  #define SHPT_POINTZ         11      
--  #define SHPT_ARCZ           13
--  #define SHPT_POLYGONZ               15
--  #define SHPT_MULTIPOINTZ    18
--
--  2D + Measure Types:
--
--  #define SHPT_POINTM         21
--  #define SHPT_ARCM           23
--  #define SHPT_POLYGONM               25
--  #define SHPT_MULTIPOINTM    28
--
--  Complex (TIN-like) with Z, and Measure:
--
--  #define SHPT_MULTIPATCH     31
--</pre>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPObject</h2>
--
--An individual shape is represented by the SHPObject structure.  SHPObject's
--created with SHPCreateObject(), SHPCreateSimpleObject(), or SHPReadObject()
--should be disposed of with SHPDestroyObject().<p>
--
--<pre>
--  typedef struct
--  {
--    int               nSHPType;       Shape Type (SHPT_* - see list above)
--
--    int               nShapeId;       Shape Number (-1 is unknown/unassigned)
--
--    int               nParts;         # of Parts (0 implies single part with no info)
--    int               *panPartStart;  Start Vertex of part
--    int               *panPartType;   Part Type (SHPP_RING if not SHPT_MULTIPATCH)
--    
--    int               nVertices;      Vertex list 
--    double    *padfX;         
--    double    *padfY;
--    double    *padfZ;         (all zero if not provided)
--    double    *padfM;         (all zero if not provided)
--
--    double    dfXMin;         Bounds in X, Y, Z and M dimensions
--    double    dfYMin;
--    double    dfZMin;
--    double    dfMMin;
--
--    double    dfXMax;
--    double    dfYMax;
--    double    dfZMax;
--    double    dfMMax;
--  } SHPObject;
--</pre>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPOpen()</h2>
--
--<pre>
--SHPHandle SHPOpen( const char * pszShapeFile, const char * pszAccess );
--
--  pszShapeFile:               The name of the layer to access.  This can be the
--                      name of either the .shp or the .shx file or can
--                      just be the path plus the basename of the pair.
--
--  pszAccess:          The fopen() style access string.  At this time only
--                      "rb" (read-only binary) and "rb+" (read/write binary) 
--                      should be used.
--</pre>
--
--  The SHPOpen() function should be used to establish access to the two files
--  for accessing vertices (.shp and .shx).  Note that both files have to 
--  be in the indicated directory, and must have the expected extensions in
--  lower case.  The returned SHPHandle is passed to other access functions, 
--  and SHPClose() should be invoked to recover resources, and flush changes 
--  to disk when complete.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPGetInfo()</h2>
--
--<pre>
--void SHPGetInfo( SHPHandle hSHP, int * pnEntities, int * pnShapeType,
--                 double * padfMinBound, double * padfMaxBound );
--
--  hSHP:                       The handle previously returned by SHPOpen() 
--                      or SHPCreate().
--
--  pnEntities:         A pointer to an integer into which the number of
--                      entities/structures should be placed.  May be NULL.
--
--  pnShapetype:                A pointer to an integer into which the shapetype
--                      of this file should be placed.  Shapefiles may contain
--                      either SHPT_POINT, SHPT_ARC, SHPT_POLYGON or 
--                      SHPT_MULTIPOINT entities.  This may be NULL.
--
--  padfMinBound:               The X, Y, Z and M minimum values will be placed into
--                        this four entry array.  This may be NULL.
--                      
--  padfMaxBound:               The X, Y, Z and M maximum values will be placed into
--                        this four entry array.  This may be NULL.
--</pre>
--
-- The SHPGetInfo() function retrieves various information about shapefile
-- as a whole.  The bounds are read from the file header, and may be 
-- inaccurate if the file was improperly generated. <p>
--                      
--<!-------------------------------------------------------------------------->
--
--<h2>SHPReadObject()</h2>
--
--<pre>
--SHPObject *SHPReadObject( SHPHandle hSHP, int iShape );
--
--  hSHP:                       The handle previously returned by SHPOpen() 
--                      or SHPCreate().
--
--  iShape:             The entity number of the shape to read.  Entity 
--                      numbers are between 0 and nEntities-1 (as returned
--                      by SHPGetInfo()).
--</pre>
--
--  The SHPReadObject() call is used to read a single structure, or entity
--  from the shapefile.  See the definition of the SHPObject structure for
--  detailed information on fields of a SHPObject.  SHPObject's returned from
--  SHPReadObject() should be deallocated with SHPDestroyShape().  
--  SHPReadObject() will return NULL if an illegal iShape value is requested.<p>
--
--  Note that the bounds placed into the SHPObject are those read from the
--  file, and may not be correct.   For points the bounds are generated from
--  the single point since bounds aren't normally provided for point types.<p>
--
--  Generally the shapes returned will be of the type of the file as a whole.
--  However, any file may also contain type SHPT_NULL shapes which will have
--  no geometry.  Generally speaking applications should skip rather than
--  preserve them, as they usually represented interactively deleted shapes.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPClose()</h2>
--
--<pre>
--void  SHPClose( SHPHandle hSHP );
--
--  hSHP:                       The handle previously returned by SHPOpen() 
--                      or SHPCreate().
--</pre>
--
--  The SHPClose() function will close the .shp and .shx files, and flush
--  all outstanding header information to the files.  It will also recover
--  resources associated with the handle.  After this call the hSHP handle
--  cannot be used again.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPCreate()</h2>
--
--<pre>
--SHPHandle SHPCreate( const char * pszShapeFile, int nShapeType );
--
--  pszShapeFile:               The name of the layer to access.  This can be the
--                      name of either the .shp or the .shx file or can
--                      just be the path plus the basename of the pair.
--
--  nShapeType:         The type of shapes to be stored in the newly created
--                      file.  It may be either SHPT_POINT, SHPT_ARC, 
--                      SHPT_POLYGON or SHPT_MULTIPOINT.
--</pre>
--
--  The SHPCreate() function will create a new .shp and .shx file of the
--  desired type.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPCreateSimpleObject()</h2>
--
--<pre>
--SHPObject * 
--     SHPCreateSimpleObject( int nSHPType, int nVertices, 
--                          double *padfX, double * padfY, double *padfZ, );
--
--  nSHPType:           The SHPT_ type of the object to be created, such
--                        as SHPT_POINT, or SHPT_POLYGON.
--  
--  nVertices:          The number of vertices being passed in padfX,    
--                        padfY, and padfZ. 
--
--  padfX:              An array of nVertices X coordinates of the vertices
--                        for this object.
--
--  padfY:              An array of nVertices Y coordinates of the vertices
--                        for this object.
--
--  padfZ:              An array of nVertices Z coordinates of the vertices
--                        for this object.  This may be NULL in which case
--                      they are all assumed to be zero.
--</pre>
--
--  The SHPCreateSimpleObject() allows for the convenient creation of 
--  simple objects.  This is normally used so that the SHPObject can be
--  passed to SHPWriteObject() to write it to the file.  The simple object
--  creation API assumes an M (measure) value of zero for each vertex.  For
--  complex objects (such as polygons) it is assumed that there is only one
--  part, and that it is of the default type (SHPP_RING). <p>
--
--  Use the SHPCreateObject() function for more sophisticated objects.  The
--  SHPDestroyObject() function should be used to free resources associated with
--  an object allocated with SHPCreateSimpleObject(). <p>
--
--  This function computes a bounding box for the SHPObject from the given 
--  vertices.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPCreateObject()</h2>
--
--<pre>
--SHPObject * 
--     SHPCreateObject( int nSHPType, int iShape,
--                      int nParts, int * panPartStart, int * panPartType,
--                      int nVertices, double *padfX, double * padfY, 
--                      double *padfZ, double *padfM );
--
--  nSHPType:           The SHPT_ type of the object to be created, such
--                        as SHPT_POINT, or SHPT_POLYGON.
--
--  iShape:             The shapeid to be recorded with this shape.
--
--  nParts:             The number of parts for this object.  If this is
--                        zero for ARC, or POLYGON type objects, a single 
--                        zero valued part will be created internally.
--  
--  panPartStart:               The list of zero based start vertices for the rings
--                        (parts) in this object.  The first should always be
--                        zero.  This may be NULL if nParts is 0.
--  
--  panPartType:                The type of each of the parts.  This is only meaningful
--                        for MULTIPATCH files.  For all other cases this may
--                        be NULL, and will be assumed to be SHPP_RING.
--  
--  nVertices:          The number of vertices being passed in padfX,    
--                        padfY, and padfZ. 
--
--  padfX:              An array of nVertices X coordinates of the vertices
--                        for this object.
--
--  padfY:              An array of nVertices Y coordinates of the vertices
--                        for this object.
--
--  padfZ:              An array of nVertices Z coordinates of the vertices
--                        for this object.  This may be NULL in which case
--                      they are all assumed to be zero.
--
--  padfM:              An array of nVertices M (measure values) of the 
--                      vertices for this object.  This may be NULL in which 
--                      case they are all assumed to be zero.
--</pre>
--
--  The SHPCreateSimpleObject() allows for the creation of objects (shapes).  
--  This is normally used so that the SHPObject can be passed to 
--  SHPWriteObject() to write it to the file. <p>
--
--  The SHPDestroyObject() function should be used to free resources associated 
--  with an object allocated with SHPCreateObject(). <p>
--
--  This function computes a bounding box for the SHPObject from the given 
--  vertices.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPComputeExtents()</h2>
--
--<pre>
--void SHPComputeExtents( SHPObject * psObject );
--
--  psObject:           An existing shape object to be updated in place.
--</pre>
-- 
--  This function will recompute the extents of this shape, replacing the
--  existing values of the dfXMin, dfYMin, dfZMin, dfMMin, dfXMax, dfYMax, 
--  dfZMax, and dfMMax values based on the current set of vertices for the
--  shape.   This function is automatically called by SHPCreateObject() but
--  if the vertices of an existing object are altered it should be called again
--  to fix up the extents.<p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPWriteObject()</h2>
--
--<pre>
--int SHPWriteObject( SHPHandle hSHP, int iShape, SHPObject *psObject );
--
--  hSHP:                       The handle previously returned by SHPOpen("r+") 
--                      or SHPCreate().
--
--  iShape:             The entity number of the shape to write.  A value of
--                      -1 should be used for new shapes.  
--
--  psObject:           The shape to write to the file. This should have
--                        been created with SHPCreateObject(), or 
--                        SHPCreateSimpleObject().
--</pre>
--
--  The SHPWriteObject() call is used to write a single structure, or entity
--  to the shapefile.  See the definition of the SHPObject structure for
--  detailed information on fields of a SHPObject.  The return value is the
--  entity number of the written shape. <p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPDestroyObject()</h2>
--
--<pre>
--void SHPDestroyObject( SHPObject *psObject );
--
--  psObject:           The object to deallocate.
--</pre>
--
--  This function should be used to deallocate the resources associated with
--  a SHPObject when it is no longer needed, including those created with
--  SHPCreateSimpleObject(), SHPCreateObject() and returned from SHPReadObject().
--  <p>
--
--<!-------------------------------------------------------------------------->
--
--<h2>SHPRewindObject()</h2>
--
--<pre>
--int SHPRewindObject( SHPHandle hSHP, SHPObject *psObject );
--
--  hSHP:                 The shapefile (not used at this time).
--  psObject:           The object to deallocate.
--</pre>
--
--  This function will reverse any rings necessary in order to enforce the
--  shapefile restrictions on the required order of inner and outer rings in
--  the Shapefile specification.  It returns TRUE if a change is made and FALSE
--  if no change is made.  Only polygon objects will be affected though any   
--  object may be passed.
--  <p>
--
--</body>
--</html>
diff --cc shapelib/shpopen.c
index 2fcff96dabae68aeb7b33b65cadf105328645176,2fcff96dabae68aeb7b33b65cadf105328645176..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,3125 -1,3125 +1,0 @@@
--/******************************************************************************
-- * $Id: shpopen.c,v 1.78 2019-02-28 15:55:23 erouault Exp $
-- *
-- * Project:  Shapelib
-- * Purpose:  Implementation of core Shapefile read/write functions.
-- * Author:   Frank Warmerdam, warmerdam@pobox.com
-- *
-- ******************************************************************************
-- * Copyright (c) 1999, 2001, Frank Warmerdam
-- * Copyright (c) 2011-2013, Even Rouault <even dot rouault at mines-paris dot org>
-- *
-- * This software is available under the following "MIT Style" license,
-- * or at the option of the licensee under the LGPL (see COPYING).  This
-- * option is discussed in more detail in shapelib.html.
-- *
-- * --
-- *
-- * Permission is hereby granted, free of charge, to any person obtaining a
-- * copy of this software and associated documentation files (the "Software"),
-- * to deal in the Software without restriction, including without limitation
-- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- * and/or sell copies of the Software, and to permit persons to whom the
-- * Software is furnished to do so, subject to the following conditions:
-- *
-- * The above copyright notice and this permission notice shall be included
-- * in all copies or substantial portions of the Software.
-- *
-- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- * DEALINGS IN THE SOFTWARE.
-- ******************************************************************************
-- *
-- * $Log: shpopen.c,v $
-- * Revision 1.78  2019-02-28 15:55:23  erouault
-- * * shpopen.c: resync with GDAL internal shapelib to avoid being dependent
-- * on correctness of file size field in .shp. Fixes
-- * https://lists.osgeo.org/pipermail/gdal-dev/2018-October/049218.html
-- *
-- * Revision 1.77  2018-08-16 15:39:07  erouault
-- * * shpopen.c, dbfopen.c, shptree.c, sbnsearch.c: resyc with GDAL
-- * internal shapelib. Mostly to allow building those files as C++
-- * without warning. Also add FTDate entry in DBFFieldType
-- * (see https://github.com/OSGeo/gdal/pull/308). And some other
-- * code cleanups
-- *
-- * Revision 1.76  2017-09-10 10:11:36  erouault
-- * * shpopen.c: resync with GDAL copy. Make sure to zero terminate all
-- * error messages. And fix regression regarding re-writing the last shape
-- * of a file (https://trac.osgeo.org/gdal/ticket/7031)
-- *
-- * Revision 1.75  2016-12-05 12:44:05  erouault
-- * * Major overhaul of Makefile build system to use autoconf/automake.
-- *
-- * * Warning fixes in contrib/
-- *
-- * Revision 1.74  2016-12-04 15:30:15  erouault
-- * * shpopen.c, dbfopen.c, shptree.c, shapefil.h: resync with
-- * GDAL Shapefile driver. Mostly cleanups. SHPObject and DBFInfo
-- * structures extended with new members. New functions:
-- * DBFSetLastModifiedDate, SHPOpenLLEx, SHPRestoreSHX,
-- * SHPSetFastModeReadObject
-- *
-- * * sbnsearch.c: new file to implement original ESRI .sbn spatial
-- * index reading. (no write support). New functions:
-- * SBNOpenDiskTree, SBNCloseDiskTree, SBNSearchDiskTree,
-- * SBNSearchDiskTreeInteger, SBNSearchFreeIds
-- *
-- * * Makefile, makefile.vc, CMakeLists.txt, shapelib.def: updates
-- * with new file and symbols.
-- *
-- * * commit: helper script to cvs commit
-- *
-- * Revision 1.73  2012-01-24 22:33:01  fwarmerdam
-- * fix memory leak on failure to open .shp (gdal #4410)
-- *
-- * Revision 1.72  2011-12-11 22:45:28  fwarmerdam
-- * fix failure return from SHPOpenLL.
-- *
-- * Revision 1.71  2011-09-15 03:33:58  fwarmerdam
-- * fix missing cast (#2344)
-- *
-- * Revision 1.70  2011-07-24 05:59:25  fwarmerdam
-- * minimize use of CPLError in favor of SAHooks.Error()
-- *
-- * Revision 1.69  2011-07-24 03:24:22  fwarmerdam
-- * fix memory leaks in error cases creating shapefiles (#2061)
-- *
-- * Revision 1.68  2010-08-27 23:42:52  fwarmerdam
-- * add SHPAPI_CALL attribute in code
-- *
-- * Revision 1.67  2010-07-01 08:15:48  fwarmerdam
-- * do not error out on an object with zero vertices
-- *
-- * Revision 1.66  2010-07-01 07:58:57  fwarmerdam
-- * minor cleanup of error handling
-- *
-- * Revision 1.65  2010-07-01 07:27:13  fwarmerdam
-- * white space formatting adjustments
-- *
-- * Revision 1.64  2010-01-28 11:34:34  fwarmerdam
-- * handle the shape file length limits more gracefully (#3236)
-- *
-- * Revision 1.63  2010-01-28 04:04:40  fwarmerdam
-- * improve numerical accuracy of SHPRewind() algs (gdal #3363)
-- *
-- * Revision 1.62  2010-01-17 05:34:13  fwarmerdam
-- * Remove asserts on x/y being null (#2148).
-- *
-- * Revision 1.61  2010-01-16 05:07:42  fwarmerdam
-- * allow 0/nulls in shpcreateobject (#2148)
-- *
-- * Revision 1.60  2009-09-17 20:50:02  bram
-- * on Win32, define snprintf as alias to _snprintf
-- *
-- * Revision 1.59  2008-03-14 05:25:31  fwarmerdam
-- * Correct crash on buggy geometries (gdal #2218)
-- *
-- * Revision 1.58  2008/01/08 23:28:26  bram
-- * on line 2095, use a float instead of a double to avoid a compiler warning
-- *
-- * Revision 1.57  2007/12/06 07:00:25  fwarmerdam
-- * dbfopen now using SAHooks for fileio
-- *
-- * Revision 1.56  2007/12/04 20:37:56  fwarmerdam
-- * preliminary implementation of hooks api for io and errors
-- *
-- * Revision 1.55  2007/11/21 22:39:56  fwarmerdam
-- * close shx file in readonly mode (GDAL #1956)
-- *
-- * Revision 1.54  2007/11/15 00:12:47  mloskot
-- * Backported recent changes from GDAL (Ticket #1415) to Shapelib.
-- *
-- * Revision 1.53  2007/11/14 22:31:08  fwarmerdam
-- * checks after mallocs to detect for corrupted/voluntary broken shapefiles.
-- * http://trac.osgeo.org/gdal/ticket/1991
-- *
-- * Revision 1.52  2007/06/21 15:58:33  fwarmerdam
-- * fix for SHPRewindObject when rings touch at one vertex (gdal #976)
-- *
-- * Revision 1.51  2006/09/04 15:24:01  fwarmerdam
-- * Fixed up log message for 1.49.
-- *
-- * Revision 1.50  2006/09/04 15:21:39  fwarmerdam
-- * fix of last fix
-- *
-- * Revision 1.49  2006/09/04 15:21:00  fwarmerdam
-- * MLoskot: Added stronger test of Shapefile reading failures, e.g. truncated
-- * files.  The problem was discovered by Tim Sutton and reported here
-- *   https://svn.qgis.org/trac/ticket/200
-- *
-- * Revision 1.48  2006/01/26 15:07:32  fwarmerdam
-- * add bMeasureIsUsed flag from Craig Bruce: Bug 1249
-- *
-- * Revision 1.47  2006/01/04 20:07:23  fwarmerdam
-- * In SHPWriteObject() make sure that the record length is updated
-- * when rewriting an existing record.
-- *
-- * Revision 1.46  2005/02/11 17:17:46  fwarmerdam
-- * added panPartStart[0] validation
-- *
-- * Revision 1.45  2004/09/26 20:09:48  fwarmerdam
-- * const correctness changes
-- *
-- * Revision 1.44  2003/12/29 00:18:39  fwarmerdam
-- * added error checking for failed IO and optional CPL error reporting
-- *
-- * Revision 1.43  2003/12/01 16:20:08  warmerda
-- * be careful of zero vertex shapes
-- *
-- * Revision 1.42  2003/12/01 14:58:27  warmerda
-- * added degenerate object check in SHPRewindObject()
-- *
-- * Revision 1.41  2003/07/08 15:22:43  warmerda
-- * avoid warning
-- *
-- * Revision 1.40  2003/04/21 18:30:37  warmerda
-- * added header write/update public methods
-- *
-- * Revision 1.39  2002/08/26 06:46:56  warmerda
-- * avoid c++ comments
-- *
-- * Revision 1.38  2002/05/07 16:43:39  warmerda
-- * Removed debugging printf()
-- *
-- * Revision 1.37  2002/04/10 17:35:22  warmerda
-- * fixed bug in ring reversal code
-- *
-- * Revision 1.36  2002/04/10 16:59:54  warmerda
-- * added SHPRewindObject
-- *
-- * Revision 1.35  2001/12/07 15:10:44  warmerda
-- * fix if .shx fails to open
-- *
-- * Revision 1.34  2001/11/01 16:29:55  warmerda
-- * move pabyRec into SHPInfo for thread safety
-- *
-- * Revision 1.33  2001/07/03 12:18:15  warmerda
-- * Improved cleanup if SHX not found, provided by Riccardo Cohen.
-- *
-- * Revision 1.32  2001/06/22 01:58:07  warmerda
-- * be more careful about establishing initial bounds in face of NULL shapes
-- *
-- * Revision 1.31  2001/05/31 19:35:29  warmerda
-- * added support for writing null shapes
-- *
-- * Revision 1.30  2001/05/28 12:46:29  warmerda
-- * Add some checking on reasonableness of record count when opening.
-- *
-- * Revision 1.29  2001/05/23 13:36:52  warmerda
-- * added use of SHPAPI_CALL
-- *
-- * Revision 1.28  2001/02/06 22:25:06  warmerda
-- * fixed memory leaks when SHPOpen() fails
-- *
-- * Revision 1.27  2000/07/18 15:21:33  warmerda
-- * added better enforcement of -1 for append in SHPWriteObject
-- *
-- * Revision 1.26  2000/02/16 16:03:51  warmerda
-- * added null shape support
-- *
-- * Revision 1.25  1999/12/15 13:47:07  warmerda
-- * Fixed record size settings in .shp file (was 4 words too long)
-- * Added stdlib.h.
-- *
-- * Revision 1.24  1999/11/05 14:12:04  warmerda
-- * updated license terms
-- *
-- * Revision 1.23  1999/07/27 00:53:46  warmerda
-- * added support for rewriting shapes
-- *
-- * Revision 1.22  1999/06/11 19:19:11  warmerda
-- * Cleanup pabyRec static buffer on SHPClose().
-- *
-- * Revision 1.21  1999/06/02 14:57:56  kshih
-- * Remove unused variables
-- *
-- * Revision 1.20  1999/04/19 21:04:17  warmerda
-- * Fixed syntax error.
-- *
-- * Revision 1.19  1999/04/19 21:01:57  warmerda
-- * Force access string to binary in SHPOpen().
-- *
-- * Revision 1.18  1999/04/01 18:48:07  warmerda
-- * Try upper case extensions if lower case doesn't work.
-- *
-- * Revision 1.17  1998/12/31 15:29:39  warmerda
-- * Disable writing measure values to multipatch objects if
-- * DISABLE_MULTIPATCH_MEASURE is defined.
-- *
-- * Revision 1.16  1998/12/16 05:14:33  warmerda
-- * Added support to write MULTIPATCH.  Fixed reading Z coordinate of
-- * MULTIPATCH. Fixed record size written for all feature types.
-- *
-- * Revision 1.15  1998/12/03 16:35:29  warmerda
-- * r+b is proper binary access string, not rb+.
-- *
-- * Revision 1.14  1998/12/03 15:47:56  warmerda
-- * Fixed setting of nVertices in SHPCreateObject().
-- *
-- * Revision 1.13  1998/12/03 15:33:54  warmerda
-- * Made SHPCalculateExtents() separately callable.
-- *
-- * Revision 1.12  1998/11/11 20:01:50  warmerda
-- * Fixed bug writing ArcM/Z, and PolygonM/Z for big endian machines.
-- *
-- * Revision 1.11  1998/11/09 20:56:44  warmerda
-- * Fixed up handling of file wide bounds.
-- *
-- * Revision 1.10  1998/11/09 20:18:51  warmerda
-- * Converted to support 3D shapefiles, and use of SHPObject.
-- *
-- * Revision 1.9  1998/02/24 15:09:05  warmerda
-- * Fixed memory leak.
-- *
-- * Revision 1.8  1997/12/04 15:40:29  warmerda
-- * Fixed byte swapping of record number, and record length fields in the
-- * .shp file.
-- *
-- * Revision 1.7  1995/10/21 03:15:58  warmerda
-- * Added support for binary file access, the magic cookie 9997
-- * and tried to improve the int32 selection logic for 16bit systems.
-- *
-- * Revision 1.6  1995/09/04  04:19:41  warmerda
-- * Added fix for file bounds.
-- *
-- * Revision 1.5  1995/08/25  15:16:44  warmerda
-- * Fixed a couple of problems with big endian systems ... one with bounds
-- * and the other with multipart polygons.
-- *
-- * Revision 1.4  1995/08/24  18:10:17  warmerda
-- * Switch to use SfRealloc() to avoid problems with pre-ANSI realloc()
-- * functions (such as on the Sun).
-- *
-- * Revision 1.3  1995/08/23  02:23:15  warmerda
-- * Added support for reading bounds, and fixed up problems in setting the
-- * file wide bounds.
-- *
-- * Revision 1.2  1995/08/04  03:16:57  warmerda
-- * Added header.
-- *
-- */
--
--#include "shapefil.h"
--
--#include <math.h>
--#include <limits.h>
--#include <assert.h>
--#include <stdlib.h>
--#include <string.h>
--#include <stdio.h>
--#include <errno.h>
--
--SHP_CVSID("$Id: shpopen.c,v 1.78 2019-02-28 15:55:23 erouault Exp $")
--
--typedef unsigned char uchar;
--
--#if UINT_MAX == 65535
--typedef unsigned long       int32;
--#else
--typedef unsigned int        int32;
--#endif
--
--#ifndef FALSE
--#  define FALSE               0
--#  define TRUE                1
--#endif
--
--#define ByteCopy( a, b, c )   memcpy( b, a, c )
--#ifndef MAX
--#  define MIN(a,b)      ((a<b) ? a : b)
--#  define MAX(a,b)      ((a>b) ? a : b)
--#endif
--
--#ifndef USE_CPL
--#if defined(_MSC_VER)
--# if _MSC_VER < 1900
--#     define snprintf _snprintf
--# endif
--#elif defined(WIN32) || defined(_WIN32)
--#  ifndef snprintf
--#     define snprintf _snprintf
--#  endif
--#endif
--#endif
--
--#ifndef CPL_UNUSED
--#if defined(__GNUC__) && __GNUC__ >= 4
--#  define CPL_UNUSED __attribute((__unused__))
--#else
--#  define CPL_UNUSED
--#endif
--#endif  
--
--#if defined(CPL_LSB)
--#define bBigEndian FALSE
--#elif defined(CPL_MSB)
--#define bBigEndian TRUE
--#else
--static int    bBigEndian;
--#endif
--
--#ifdef __cplusplus
--#define STATIC_CAST(type,x) static_cast<type>(x)
--#define SHPLIB_NULLPTR nullptr
--#else
--#define STATIC_CAST(type,x) ((type)(x))
--#define SHPLIB_NULLPTR NULL
--#endif
--
--/************************************************************************/
--/*                              SwapWord()                              */
--/*                                                                      */
--/*      Swap a 2, 4 or 8 byte word.                                     */
--/************************************************************************/
--
--static void   SwapWord( int length, void * wordP )
--
--{
--    int               i;
--    uchar     temp;
--
--    for( i=0; i < length/2; i++ )
--    {
--      temp = STATIC_CAST(uchar*, wordP)[i];
--      STATIC_CAST(uchar*, wordP)[i] = STATIC_CAST(uchar*, wordP)[length-i-1];
--      STATIC_CAST(uchar*, wordP)[length-i-1] = temp;
--    }
--}
--
--/************************************************************************/
--/*                             SfRealloc()                              */
--/*                                                                      */
--/*      A realloc cover function that will access a NULL pointer as     */
--/*      a valid input.                                                  */
--/************************************************************************/
--
--static void * SfRealloc( void * pMem, int nNewSize )
--
--{
--    if( pMem == SHPLIB_NULLPTR )
--        return malloc(nNewSize);
--    else
--        return realloc(pMem,nNewSize);
--}
--
--/************************************************************************/
--/*                          SHPWriteHeader()                            */
--/*                                                                      */
--/*      Write out a header for the .shp and .shx files as well as the */
--/*    contents of the index (.shx) file.                              */
--/************************************************************************/
--
--void SHPAPI_CALL SHPWriteHeader( SHPHandle psSHP )
--
--{
--    uchar             abyHeader[100] = { 0 };
--    int               i;
--    int32     i32;
--    double    dValue;
--    int32     *panSHX;
--
--    if (psSHP->fpSHX == SHPLIB_NULLPTR)
--    {
--        psSHP->sHooks.Error( "SHPWriteHeader failed : SHX file is closed");
--        return;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Prepare header block for .shp file.                             */
--/* -------------------------------------------------------------------- */
--
--    abyHeader[2] = 0x27;                              /* magic cookie */
--    abyHeader[3] = 0x0a;
--
--    i32 = psSHP->nFileSize/2;                         /* file size */
--    ByteCopy( &i32, abyHeader+24, 4 );
--    if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
--
--    i32 = 1000;                                               /* version */
--    ByteCopy( &i32, abyHeader+28, 4 );
--    if( bBigEndian ) SwapWord( 4, abyHeader+28 );
--
--    i32 = psSHP->nShapeType;                          /* shape type */
--    ByteCopy( &i32, abyHeader+32, 4 );
--    if( bBigEndian ) SwapWord( 4, abyHeader+32 );
--
--    dValue = psSHP->adBoundsMin[0];                   /* set bounds */
--    ByteCopy( &dValue, abyHeader+36, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+36 );
--
--    dValue = psSHP->adBoundsMin[1];
--    ByteCopy( &dValue, abyHeader+44, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+44 );
--
--    dValue = psSHP->adBoundsMax[0];
--    ByteCopy( &dValue, abyHeader+52, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+52 );
--
--    dValue = psSHP->adBoundsMax[1];
--    ByteCopy( &dValue, abyHeader+60, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+60 );
--
--    dValue = psSHP->adBoundsMin[2];                   /* z */
--    ByteCopy( &dValue, abyHeader+68, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+68 );
--
--    dValue = psSHP->adBoundsMax[2];
--    ByteCopy( &dValue, abyHeader+76, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+76 );
--
--    dValue = psSHP->adBoundsMin[3];                   /* m */
--    ByteCopy( &dValue, abyHeader+84, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+84 );
--
--    dValue = psSHP->adBoundsMax[3];
--    ByteCopy( &dValue, abyHeader+92, 8 );
--    if( bBigEndian ) SwapWord( 8, abyHeader+92 );
--
--/* -------------------------------------------------------------------- */
--/*      Write .shp file header.                                         */
--/* -------------------------------------------------------------------- */
--    if( psSHP->sHooks.FSeek( psSHP->fpSHP, 0, 0 ) != 0
--        || psSHP->sHooks.FWrite( abyHeader, 100, 1, psSHP->fpSHP ) != 1 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failure writing .shp header: %s", strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--        return;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Prepare, and write .shx file header.                            */
--/* -------------------------------------------------------------------- */
--    i32 = (psSHP->nRecords * 2 * sizeof(int32) + 100)/2;   /* file size */
--    ByteCopy( &i32, abyHeader+24, 4 );
--    if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
--
--    if( psSHP->sHooks.FSeek( psSHP->fpSHX, 0, 0 ) != 0
--        || psSHP->sHooks.FWrite( abyHeader, 100, 1, psSHP->fpSHX ) != 1 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failure writing .shx header: %s", strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--
--        return;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Write out the .shx contents.                                    */
--/* -------------------------------------------------------------------- */
--    panSHX = STATIC_CAST(int32 *, malloc(sizeof(int32) * 2 * psSHP->nRecords));
--    if( panSHX == SHPLIB_NULLPTR )
--    {
--        psSHP->sHooks.Error( "Failure allocatin panSHX" );
--        return;
--    }
--
--    for( i = 0; i < psSHP->nRecords; i++ )
--    {
--        panSHX[i*2  ] = psSHP->panRecOffset[i]/2;
--        panSHX[i*2+1] = psSHP->panRecSize[i]/2;
--        if( !bBigEndian ) SwapWord( 4, panSHX+i*2 );
--        if( !bBigEndian ) SwapWord( 4, panSHX+i*2+1 );
--    }
--
--    if( STATIC_CAST(int, psSHP->sHooks.FWrite( panSHX, sizeof(int32)*2, psSHP->nRecords, psSHP->fpSHX ))
--        != psSHP->nRecords )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failure writing .shx contents: %s", strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--    }
--
--    free( panSHX );
--
--/* -------------------------------------------------------------------- */
--/*      Flush to disk.                                                  */
--/* -------------------------------------------------------------------- */
--    psSHP->sHooks.FFlush( psSHP->fpSHP );
--    psSHP->sHooks.FFlush( psSHP->fpSHX );
--}
--
--/************************************************************************/
--/*                              SHPOpen()                               */
--/************************************************************************/
--
--SHPHandle SHPAPI_CALL
--SHPOpen( const char * pszLayer, const char * pszAccess )
--
--{
--    SAHooks sHooks;
--
--    SASetupDefaultHooks( &sHooks );
--
--    return SHPOpenLL( pszLayer, pszAccess, &sHooks );
--}
--
--/************************************************************************/
--/*                      SHPGetLenWithoutExtension()                     */
--/************************************************************************/
--
--static int SHPGetLenWithoutExtension(const char* pszBasename)
--{
--    int i;
--    int nLen = STATIC_CAST(int, strlen(pszBasename));
--    for( i = nLen-1;
--         i > 0 && pszBasename[i] != '/' && pszBasename[i] != '\\';
--         i-- )
--    {
--        if( pszBasename[i] == '.' )
--        {
--            return i;
--        }
--    }
--    return nLen;
--}
--
--/************************************************************************/
--/*                              SHPOpen()                               */
--/*                                                                      */
--/*      Open the .shp and .shx files based on the basename of the       */
--/*      files or either file name.                                      */
--/************************************************************************/
--
--SHPHandle SHPAPI_CALL
--SHPOpenLL( const char * pszLayer, const char * pszAccess, SAHooks *psHooks )
--
--{
--    char        *pszFullname;
--    SHPHandle       psSHP;
--
--    uchar       *pabyBuf;
--    int         i;
--    double      dValue;
--    int         bLazySHXLoading = FALSE;
--    int         nLenWithoutExtension;
--
--/* -------------------------------------------------------------------- */
--/*      Ensure the access string is one of the legal ones.  We          */
--/*      ensure the result string indicates binary to avoid common       */
--/*      problems on Windows.                                            */
--/* -------------------------------------------------------------------- */
--    if( strcmp(pszAccess,"rb+") == 0 || strcmp(pszAccess,"r+b") == 0
--        || strcmp(pszAccess,"r+") == 0 )
--        pszAccess = "r+b";
--    else
--    {
--        bLazySHXLoading = strchr(pszAccess, 'l') != SHPLIB_NULLPTR;
--        pszAccess = "rb";
--    }
--
--/* -------------------------------------------------------------------- */
--/*  Establish the byte order on this machine.           */
--/* -------------------------------------------------------------------- */
--#if !defined(bBigEndian)
--    i = 1;
--    if( *((uchar *) &i) == 1 )
--        bBigEndian = FALSE;
--    else
--        bBigEndian = TRUE;
--#endif
--
--/* -------------------------------------------------------------------- */
--/*  Initialize the info structure.                  */
--/* -------------------------------------------------------------------- */
--    psSHP = STATIC_CAST(SHPHandle, calloc(sizeof(SHPInfo),1));
--
--    psSHP->bUpdated = FALSE;
--    memcpy( &(psSHP->sHooks), psHooks, sizeof(SAHooks) );
--
--/* -------------------------------------------------------------------- */
--/*  Open the .shp and .shx files.  Note that files pulled from  */
--/*  a PC to Unix with upper case filenames won't work!      */
--/* -------------------------------------------------------------------- */
--    nLenWithoutExtension = SHPGetLenWithoutExtension(pszLayer);
--    pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5));
--    memcpy(pszFullname, pszLayer, nLenWithoutExtension);
--    memcpy(pszFullname + nLenWithoutExtension, ".shp", 5);
--    psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess );
--    if( psSHP->fpSHP == SHPLIB_NULLPTR )
--    {
--        memcpy(pszFullname + nLenWithoutExtension, ".SHP", 5);
--        psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess );
--    }
--
--    if( psSHP->fpSHP == SHPLIB_NULLPTR )
--    {
--        size_t nMessageLen = strlen(pszFullname)*2+256;
--        char *pszMessage = STATIC_CAST(char *, malloc(nMessageLen));
--        pszFullname[nLenWithoutExtension] = 0;
--        snprintf( pszMessage, nMessageLen, "Unable to open %s.shp or %s.SHP.",
--                  pszFullname, pszFullname );
--        psHooks->Error( pszMessage );
--        free( pszMessage );
--
--        free( psSHP );
--        free( pszFullname );
--
--        return SHPLIB_NULLPTR;
--    }
--
--    memcpy(pszFullname + nLenWithoutExtension, ".shx", 5);
--    psSHP->fpSHX =  psSHP->sHooks.FOpen(pszFullname, pszAccess );
--    if( psSHP->fpSHX == SHPLIB_NULLPTR )
--    {
--        memcpy(pszFullname + nLenWithoutExtension, ".SHX", 5);
--        psSHP->fpSHX = psSHP->sHooks.FOpen(pszFullname, pszAccess );
--    }
--
--    if( psSHP->fpSHX == SHPLIB_NULLPTR )
--    {
--        size_t nMessageLen = strlen(pszFullname)*2+256;
--        char *pszMessage = STATIC_CAST(char *, malloc(nMessageLen));
--        pszFullname[nLenWithoutExtension] = 0;
--        snprintf( pszMessage, nMessageLen, "Unable to open %s.shx or %s.SHX. "
--                  "Set SHAPE_RESTORE_SHX config option to YES to restore or "
--                  "create it.", pszFullname, pszFullname );
--        psHooks->Error( pszMessage );
--        free( pszMessage );
--
--        psSHP->sHooks.FClose( psSHP->fpSHP );
--        free( psSHP );
--        free( pszFullname );
--        return SHPLIB_NULLPTR ;
--    }
--
--    free( pszFullname );
--
--/* -------------------------------------------------------------------- */
--/*  Read the file size from the SHP file.               */
--/* -------------------------------------------------------------------- */
--    pabyBuf = STATIC_CAST(uchar *, malloc(100));
--    if( psSHP->sHooks.FRead( pabyBuf, 100, 1, psSHP->fpSHP ) != 1 )
--    {
--        psSHP->sHooks.Error( ".shp file is unreadable, or corrupt." );
--        psSHP->sHooks.FClose( psSHP->fpSHP );
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--        free( pabyBuf );
--        free( psSHP );
--
--        return SHPLIB_NULLPTR ;
--    }
--
--    psSHP->nFileSize = (STATIC_CAST(unsigned int, pabyBuf[24])<<24)|(pabyBuf[25]<<16)|
--                        (pabyBuf[26]<<8)|pabyBuf[27];
--    if( psSHP->nFileSize < UINT_MAX / 2 )
--        psSHP->nFileSize *= 2;
--    else
--        psSHP->nFileSize = (UINT_MAX / 2) * 2;
--
--/* -------------------------------------------------------------------- */
--/*  Read SHX file Header info                                           */
--/* -------------------------------------------------------------------- */
--    if( psSHP->sHooks.FRead( pabyBuf, 100, 1, psSHP->fpSHX ) != 1
--        || pabyBuf[0] != 0
--        || pabyBuf[1] != 0
--        || pabyBuf[2] != 0x27
--        || (pabyBuf[3] != 0x0a && pabyBuf[3] != 0x0d) )
--    {
--        psSHP->sHooks.Error( ".shx file is unreadable, or corrupt." );
--        psSHP->sHooks.FClose( psSHP->fpSHP );
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--        free( pabyBuf );
--        free( psSHP );
--
--        return SHPLIB_NULLPTR;
--    }
--
--    psSHP->nRecords = pabyBuf[27]|(pabyBuf[26]<<8)|(pabyBuf[25]<<16)|
--                      ((pabyBuf[24] & 0x7F)<<24);
--    psSHP->nRecords = (psSHP->nRecords - 50) / 4;
--
--    psSHP->nShapeType = pabyBuf[32];
--
--    if( psSHP->nRecords < 0 || psSHP->nRecords > 256000000 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Record count in .shp header is %d, which seems\n"
--                 "unreasonable.  Assuming header is corrupt.",
--                 psSHP->nRecords );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--        psSHP->sHooks.FClose( psSHP->fpSHP );
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--        free( psSHP );
--        free(pabyBuf);
--
--        return SHPLIB_NULLPTR;
--    }
--
--    /* If a lot of records are advertized, check that the file is big enough */
--    /* to hold them */
--    if( psSHP->nRecords >= 1024 * 1024 )
--    {
--        SAOffset nFileSize;
--        psSHP->sHooks.FSeek( psSHP->fpSHX, 0, 2 );
--        nFileSize = psSHP->sHooks.FTell( psSHP->fpSHX );
--        if( nFileSize > 100 &&
--            nFileSize/2 < STATIC_CAST(SAOffset, psSHP->nRecords * 4 + 50) )
--        {
--            psSHP->nRecords = STATIC_CAST(int, (nFileSize - 100) / 8);
--        }
--        psSHP->sHooks.FSeek( psSHP->fpSHX, 100, 0 );
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Read the bounds.                                                */
--/* -------------------------------------------------------------------- */
--    if( bBigEndian ) SwapWord( 8, pabyBuf+36 );
--    memcpy( &dValue, pabyBuf+36, 8 );
--    psSHP->adBoundsMin[0] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+44 );
--    memcpy( &dValue, pabyBuf+44, 8 );
--    psSHP->adBoundsMin[1] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+52 );
--    memcpy( &dValue, pabyBuf+52, 8 );
--    psSHP->adBoundsMax[0] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+60 );
--    memcpy( &dValue, pabyBuf+60, 8 );
--    psSHP->adBoundsMax[1] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+68 );     /* z */
--    memcpy( &dValue, pabyBuf+68, 8 );
--    psSHP->adBoundsMin[2] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+76 );
--    memcpy( &dValue, pabyBuf+76, 8 );
--    psSHP->adBoundsMax[2] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+84 );     /* z */
--    memcpy( &dValue, pabyBuf+84, 8 );
--    psSHP->adBoundsMin[3] = dValue;
--
--    if( bBigEndian ) SwapWord( 8, pabyBuf+92 );
--    memcpy( &dValue, pabyBuf+92, 8 );
--    psSHP->adBoundsMax[3] = dValue;
--
--    free( pabyBuf );
--
--/* -------------------------------------------------------------------- */
--/*  Read the .shx file to get the offsets to each record in     */
--/*  the .shp file.                          */
--/* -------------------------------------------------------------------- */
--    psSHP->nMaxRecords = psSHP->nRecords;
--
--    psSHP->panRecOffset = STATIC_CAST(unsigned int *,
--        malloc(sizeof(unsigned int) * MAX(1,psSHP->nMaxRecords) ));
--    psSHP->panRecSize = STATIC_CAST(unsigned int *,
--        malloc(sizeof(unsigned int) * MAX(1,psSHP->nMaxRecords) ));
--    if( bLazySHXLoading )
--        pabyBuf = SHPLIB_NULLPTR;
--    else
--        pabyBuf = STATIC_CAST(uchar *, malloc(8 * MAX(1,psSHP->nRecords) ));
--
--    if (psSHP->panRecOffset == SHPLIB_NULLPTR ||
--        psSHP->panRecSize == SHPLIB_NULLPTR ||
--        (!bLazySHXLoading && pabyBuf == SHPLIB_NULLPTR))
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                "Not enough memory to allocate requested memory (nRecords=%d).\n"
--                "Probably broken SHP file",
--                psSHP->nRecords );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--        psSHP->sHooks.FClose( psSHP->fpSHP );
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--        if (psSHP->panRecOffset) free( psSHP->panRecOffset );
--        if (psSHP->panRecSize) free( psSHP->panRecSize );
--        if (pabyBuf) free( pabyBuf );
--        free( psSHP );
--        return SHPLIB_NULLPTR;
--    }
--
--    if( bLazySHXLoading )
--    {
--        memset(psSHP->panRecOffset, 0, sizeof(unsigned int) * MAX(1,psSHP->nMaxRecords) );
--        memset(psSHP->panRecSize, 0, sizeof(unsigned int) * MAX(1,psSHP->nMaxRecords) );
--        free( pabyBuf ); // sometimes make cppcheck happy, but
--        return( psSHP );
--    }
--
--    if( STATIC_CAST(int, psSHP->sHooks.FRead( pabyBuf, 8, psSHP->nRecords, psSHP->fpSHX ))
--        != psSHP->nRecords )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failed to read all values for %d records in .shx file: %s.",
--                 psSHP->nRecords, strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--
--        /* SHX is short or unreadable for some reason. */
--        psSHP->sHooks.FClose( psSHP->fpSHP );
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--        free( psSHP->panRecOffset );
--        free( psSHP->panRecSize );
--        free( pabyBuf );
--        free( psSHP );
--
--        return SHPLIB_NULLPTR;
--    }
--
--    /* In read-only mode, we can close the SHX now */
--    if (strcmp(pszAccess, "rb") == 0)
--    {
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--        psSHP->fpSHX = SHPLIB_NULLPTR;
--    }
--
--    for( i = 0; i < psSHP->nRecords; i++ )
--    {
--        unsigned int        nOffset, nLength;
--
--        memcpy( &nOffset, pabyBuf + i * 8, 4 );
--        if( !bBigEndian ) SwapWord( 4, &nOffset );
--
--        memcpy( &nLength, pabyBuf + i * 8 + 4, 4 );
--        if( !bBigEndian ) SwapWord( 4, &nLength );
--
--        if( nOffset > STATIC_CAST(unsigned int, INT_MAX) )
--        {
--            char str[128];
--            snprintf( str, sizeof(str),
--                    "Invalid offset for entity %d", i);
--            str[sizeof(str)-1] = '\0';
--
--            psSHP->sHooks.Error( str );
--            SHPClose(psSHP);
--            free( pabyBuf );
--            return SHPLIB_NULLPTR;
--        }
--        if( nLength > STATIC_CAST(unsigned int, INT_MAX / 2 - 4) )
--        {
--            char str[128];
--            snprintf( str, sizeof(str),
--                    "Invalid length for entity %d", i);
--            str[sizeof(str)-1] = '\0';
--
--            psSHP->sHooks.Error( str );
--            SHPClose(psSHP);
--            free( pabyBuf );
--            return SHPLIB_NULLPTR;
--        }
--        psSHP->panRecOffset[i] = nOffset*2;
--        psSHP->panRecSize[i] = nLength*2;
--    }
--    free( pabyBuf );
--
--    return( psSHP );
--}
--
--/************************************************************************/
--/*                              SHPOpenLLEx()                           */
--/*                                                                      */
--/*      Open the .shp and .shx files based on the basename of the       */
--/*      files or either file name. It generally invokes SHPRestoreSHX() */
--/*      in case when bRestoreSHX equals true.                           */
--/************************************************************************/
--
--SHPHandle SHPAPI_CALL
--SHPOpenLLEx( const char * pszLayer, const char * pszAccess, SAHooks *psHooks,
--            int bRestoreSHX )
--
--{
--    if ( !bRestoreSHX ) return SHPOpenLL ( pszLayer, pszAccess, psHooks );
--    else
--    {
--        if ( SHPRestoreSHX ( pszLayer, pszAccess, psHooks ) )
--        {
--            return SHPOpenLL ( pszLayer, pszAccess, psHooks );
--        }
--    }
--
--    return SHPLIB_NULLPTR;
--}
--
--/************************************************************************/
--/*                              SHPRestoreSHX()                         */
--/*                                                                      */
--/*      Restore .SHX file using associated .SHP file.                   */
--/*                                                                      */
--/************************************************************************/
--
--int       SHPAPI_CALL
--SHPRestoreSHX ( const char * pszLayer, const char * pszAccess, SAHooks *psHooks )
--
--{
--    char            *pszFullname;
--    SAFile          fpSHP, fpSHX;
--
--
--    uchar           *pabyBuf;
--    int             nLenWithoutExtension;
--    unsigned int    nSHPFilesize;
--
--    unsigned int    nCurrentRecordOffset = 0;
--    unsigned int    nCurrentSHPOffset = 100;
--    size_t          nRealSHXContentSize = 100;
--
--    const char      pszSHXAccess[] = "w+b";
--    char            *pabySHXHeader;
--    char            abyReadedRecord[8];
--    unsigned int    niRecord = 0;
--    unsigned int    nRecordLength = 0;
--    unsigned int    nRecordOffset = 50;
--
--/* -------------------------------------------------------------------- */
--/*      Ensure the access string is one of the legal ones.  We          */
--/*      ensure the result string indicates binary to avoid common       */
--/*      problems on Windows.                                            */
--/* -------------------------------------------------------------------- */
--    if( strcmp(pszAccess,"rb+") == 0 || strcmp(pszAccess,"r+b") == 0
--        || strcmp(pszAccess,"r+") == 0 )
--        pszAccess = "r+b";
--    else
--    {
--        pszAccess = "rb";
--    }
--
--/* -------------------------------------------------------------------- */
--/*  Establish the byte order on this machine.                           */
--/* -------------------------------------------------------------------- */
--#if !defined(bBigEndian)
--    {
--        int i = 1;
--        if( *((uchar *) &i) == 1 )
--            bBigEndian = FALSE;
--        else
--            bBigEndian = TRUE;
--    }
--#endif
--
--/* -------------------------------------------------------------------- */
--/*  Open the .shp file.  Note that files pulled from                    */
--/*  a PC to Unix with upper case filenames won't work!                  */
--/* -------------------------------------------------------------------- */
--    nLenWithoutExtension = SHPGetLenWithoutExtension(pszLayer);
--    pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5));
--    memcpy(pszFullname, pszLayer, nLenWithoutExtension);
--    memcpy(pszFullname + nLenWithoutExtension, ".shp", 5);
--    fpSHP = psHooks->FOpen(pszFullname, pszAccess );
--    if( fpSHP == SHPLIB_NULLPTR )
--    {
--        memcpy(pszFullname + nLenWithoutExtension, ".SHP", 5);
--        fpSHP = psHooks->FOpen(pszFullname, pszAccess );
--    }
--
--    if( fpSHP == SHPLIB_NULLPTR )
--    {
--        size_t nMessageLen = strlen( pszFullname ) * 2 + 256;
--        char* pszMessage = STATIC_CAST(char *, malloc( nMessageLen ));
--
--        pszFullname[nLenWithoutExtension] = 0;
--        snprintf( pszMessage, nMessageLen, "Unable to open %s.shp or %s.SHP.",
--                  pszFullname, pszFullname );
--        psHooks->Error( pszMessage );
--        free( pszMessage );
--
--        free( pszFullname );
--
--        return( 0 );
--    }
--
--/* -------------------------------------------------------------------- */
--/*  Read the file size from the SHP file.                               */
--/* -------------------------------------------------------------------- */
--    pabyBuf = STATIC_CAST(uchar *, malloc(100));
--    psHooks->FRead( pabyBuf, 100, 1, fpSHP );
--
--    nSHPFilesize = (STATIC_CAST(unsigned int, pabyBuf[24])<<24)|(pabyBuf[25]<<16)|
--                   (pabyBuf[26]<<8)|pabyBuf[27];
--    if( nSHPFilesize < UINT_MAX / 2 )
--        nSHPFilesize *= 2;
--    else
--        nSHPFilesize = (UINT_MAX / 2) * 2;
--
--    memcpy(pszFullname + nLenWithoutExtension, ".shx", 5);
--    fpSHX = psHooks->FOpen( pszFullname, pszSHXAccess );
--    if( fpSHX == SHPLIB_NULLPTR )
--    {
--        memcpy(pszFullname + nLenWithoutExtension, ".SHX", 5);
--        fpSHP = psHooks->FOpen(pszFullname, pszAccess );
--    }
--
--    if( fpSHX == SHPLIB_NULLPTR )
--    {
--        size_t nMessageLen = strlen( pszFullname ) * 2 + 256;
--        char* pszMessage = STATIC_CAST(char *, malloc( nMessageLen ));
--        pszFullname[nLenWithoutExtension] = 0;
--        snprintf( pszMessage, nMessageLen,
--                  "Error opening file %s.shx or %s.SHX for writing",
--                  pszFullname, pszFullname );
--        psHooks->Error( pszMessage );
--        free( pszMessage );
--
--        psHooks->FClose( fpSHX );
--
--        free( pabyBuf );
--        free( pszFullname );
--
--        return( 0 );
--    }
--
--/* -------------------------------------------------------------------- */
--/*  Open SHX and create it using SHP file content.                      */
--/* -------------------------------------------------------------------- */
--    psHooks->FSeek( fpSHP, 100, 0 );
--    pabySHXHeader = STATIC_CAST(char *, malloc ( 100 ));
--    memcpy( pabySHXHeader, pabyBuf, 100 );
--    psHooks->FWrite( pabySHXHeader, 100, 1, fpSHX );
--
--    while( nCurrentSHPOffset < nSHPFilesize )
--    {
--        if( psHooks->FRead( &niRecord, 4, 1, fpSHP ) == 1 &&
--            psHooks->FRead( &nRecordLength, 4, 1, fpSHP ) == 1)
--        {
--            if( !bBigEndian ) SwapWord( 4, &nRecordOffset );
--            memcpy( abyReadedRecord, &nRecordOffset, 4 );
--            memcpy( abyReadedRecord + 4, &nRecordLength, 4 );
--
--            psHooks->FWrite( abyReadedRecord, 8, 1, fpSHX );
--
--            if ( !bBigEndian ) SwapWord( 4, &nRecordOffset );
--            if ( !bBigEndian ) SwapWord( 4, &nRecordLength );
--            nRecordOffset += nRecordLength + 4;
--            nCurrentRecordOffset += 8;
--            nCurrentSHPOffset += 8 + nRecordLength * 2;
--
--            psHooks->FSeek( fpSHP, nCurrentSHPOffset, 0 );
--            nRealSHXContentSize += 8;
--        }
--        else
--        {
--            psHooks->Error( "Error parsing .shp to restore .shx"  );
--
--            psHooks->FClose( fpSHX );
--            psHooks->FClose( fpSHP );
--
--            free( pabySHXHeader );
--            free( pszFullname );
--
--            return( 0 );
--        }
--    }
--
--    nRealSHXContentSize /= 2; // Bytes counted -> WORDs
--    if( !bBigEndian ) SwapWord( 4, &nRealSHXContentSize );
--    psHooks->FSeek( fpSHX, 24, 0 );
--    psHooks->FWrite( &nRealSHXContentSize, 4, 1, fpSHX );
--
--    psHooks->FClose( fpSHP );
--    psHooks->FClose( fpSHX );
--
--    free ( pabyBuf );
--    free ( pszFullname );
--    free ( pabySHXHeader );
--
--    return( 1 );
--}
--
--/************************************************************************/
--/*                              SHPClose()                              */
--/*                                                                    */
--/*    Close the .shp and .shx files.                                  */
--/************************************************************************/
--
--void SHPAPI_CALL
--SHPClose(SHPHandle psSHP )
--
--{
--    if( psSHP == SHPLIB_NULLPTR )
--        return;
--
--/* -------------------------------------------------------------------- */
--/*    Update the header if we have modified anything.                 */
--/* -------------------------------------------------------------------- */
--    if( psSHP->bUpdated )
--      SHPWriteHeader( psSHP );
--
--/* -------------------------------------------------------------------- */
--/*      Free all resources, and close files.                            */
--/* -------------------------------------------------------------------- */
--    free( psSHP->panRecOffset );
--    free( psSHP->panRecSize );
--
--    if ( psSHP->fpSHX != SHPLIB_NULLPTR)
--        psSHP->sHooks.FClose( psSHP->fpSHX );
--    psSHP->sHooks.FClose( psSHP->fpSHP );
--
--    if( psSHP->pabyRec != SHPLIB_NULLPTR )
--    {
--        free( psSHP->pabyRec );
--    }
--
--    if( psSHP->pabyObjectBuf != SHPLIB_NULLPTR )
--    {
--        free( psSHP->pabyObjectBuf );
--    }
--    if( psSHP->psCachedObject != SHPLIB_NULLPTR )
--    {
--        free( psSHP->psCachedObject );
--    }
--
--    free( psSHP );
--}
--
--/************************************************************************/
--/*                    SHPSetFastModeReadObject()                        */
--/************************************************************************/
--
--/* If setting bFastMode = TRUE, the content of SHPReadObject() is owned by the SHPHandle. */
--/* So you cannot have 2 valid instances of SHPReadObject() simultaneously. */
--/* The SHPObject padfZ and padfM members may be NULL depending on the geometry */
--/* type. It is illegal to free at hand any of the pointer members of the SHPObject structure */
--void SHPAPI_CALL SHPSetFastModeReadObject( SHPHandle hSHP, int bFastMode )
--{
--    if( bFastMode )
--    {
--        if( hSHP->psCachedObject == SHPLIB_NULLPTR )
--        {
--            hSHP->psCachedObject = STATIC_CAST(SHPObject*, calloc(1, sizeof(SHPObject)));
--            assert( hSHP->psCachedObject != SHPLIB_NULLPTR );
--        }
--    }
--
--    hSHP->bFastModeReadObject = bFastMode;
--}
--
--/************************************************************************/
--/*                             SHPGetInfo()                             */
--/*                                                                      */
--/*      Fetch general information about the shape file.                 */
--/************************************************************************/
--
--void SHPAPI_CALL
--SHPGetInfo(SHPHandle psSHP, int * pnEntities, int * pnShapeType,
--           double * padfMinBound, double * padfMaxBound )
--
--{
--    int               i;
--
--    if( psSHP == SHPLIB_NULLPTR )
--        return;
--
--    if( pnEntities != SHPLIB_NULLPTR )
--        *pnEntities = psSHP->nRecords;
--
--    if( pnShapeType != SHPLIB_NULLPTR )
--        *pnShapeType = psSHP->nShapeType;
--
--    for( i = 0; i < 4; i++ )
--    {
--        if( padfMinBound != SHPLIB_NULLPTR )
--            padfMinBound[i] = psSHP->adBoundsMin[i];
--        if( padfMaxBound != SHPLIB_NULLPTR )
--            padfMaxBound[i] = psSHP->adBoundsMax[i];
--    }
--}
--
--/************************************************************************/
--/*                             SHPCreate()                              */
--/*                                                                      */
--/*      Create a new shape file and return a handle to the open         */
--/*      shape file with read/write access.                              */
--/************************************************************************/
--
--SHPHandle SHPAPI_CALL
--SHPCreate( const char * pszLayer, int nShapeType )
--
--{
--    SAHooks sHooks;
--
--    SASetupDefaultHooks( &sHooks );
--
--    return SHPCreateLL( pszLayer, nShapeType, &sHooks );
--}
--
--/************************************************************************/
--/*                             SHPCreate()                              */
--/*                                                                      */
--/*      Create a new shape file and return a handle to the open         */
--/*      shape file with read/write access.                              */
--/************************************************************************/
--
--SHPHandle SHPAPI_CALL
--SHPCreateLL( const char * pszLayer, int nShapeType, SAHooks *psHooks )
--
--{
--    char      *pszFullname;
--    SAFile    fpSHP;
--    SAFile      fpSHX = SHPLIB_NULLPTR;
--    uchar             abyHeader[100];
--    int32     i32;
--    double    dValue;
--    int         nLenWithoutExtension;
--
--/* -------------------------------------------------------------------- */
--/*      Establish the byte order on this system.                        */
--/* -------------------------------------------------------------------- */
--#if !defined(bBigEndian)
--    {
--        int i = 1;
--        if( *((uchar *) &i) == 1 )
--            bBigEndian = FALSE;
--        else
--            bBigEndian = TRUE;
--    }
--#endif
--
--/* -------------------------------------------------------------------- */
--/*      Open the two files so we can write their headers.               */
--/* -------------------------------------------------------------------- */
--    nLenWithoutExtension = SHPGetLenWithoutExtension(pszLayer);
--    pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5));
--    memcpy(pszFullname, pszLayer, nLenWithoutExtension);
--    memcpy(pszFullname + nLenWithoutExtension, ".shp", 5);
--    fpSHP = psHooks->FOpen(pszFullname, "wb" );
--    if( fpSHP == SHPLIB_NULLPTR )
--    {
--        char szErrorMsg[200];
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failed to create file %s: %s",
--                  pszFullname, strerror(errno) );
--        psHooks->Error( szErrorMsg );
--
--        goto error;
--    }
--
--    memcpy(pszFullname + nLenWithoutExtension, ".shx", 5);
--    fpSHX = psHooks->FOpen(pszFullname, "wb" );
--    if( fpSHX == SHPLIB_NULLPTR )
--    {
--        char szErrorMsg[200];
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failed to create file %s: %s",
--                  pszFullname, strerror(errno) );
--        psHooks->Error( szErrorMsg );
--        goto error;
--    }
--
--    free( pszFullname ); pszFullname = SHPLIB_NULLPTR;
--
--/* -------------------------------------------------------------------- */
--/*      Prepare header block for .shp file.                             */
--/* -------------------------------------------------------------------- */
--    memset( abyHeader, 0, sizeof(abyHeader) );
--
--    abyHeader[2] = 0x27;                              /* magic cookie */
--    abyHeader[3] = 0x0a;
--
--    i32 = 50;                                         /* file size */
--    ByteCopy( &i32, abyHeader+24, 4 );
--    if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
--
--    i32 = 1000;                                               /* version */
--    ByteCopy( &i32, abyHeader+28, 4 );
--    if( bBigEndian ) SwapWord( 4, abyHeader+28 );
--
--    i32 = nShapeType;                                 /* shape type */
--    ByteCopy( &i32, abyHeader+32, 4 );
--    if( bBigEndian ) SwapWord( 4, abyHeader+32 );
--
--    dValue = 0.0;                                     /* set bounds */
--    ByteCopy( &dValue, abyHeader+36, 8 );
--    ByteCopy( &dValue, abyHeader+44, 8 );
--    ByteCopy( &dValue, abyHeader+52, 8 );
--    ByteCopy( &dValue, abyHeader+60, 8 );
--
--/* -------------------------------------------------------------------- */
--/*      Write .shp file header.                                         */
--/* -------------------------------------------------------------------- */
--    if( psHooks->FWrite( abyHeader, 100, 1, fpSHP ) != 1 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failed to write .shp header: %s", strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psHooks->Error( szErrorMsg );
--
--        goto error;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Prepare, and write .shx file header.                            */
--/* -------------------------------------------------------------------- */
--    i32 = 50;                                         /* file size */
--    ByteCopy( &i32, abyHeader+24, 4 );
--    if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
--
--    if( psHooks->FWrite( abyHeader, 100, 1, fpSHX ) != 1 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Failure writing .shx header: %s", strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psHooks->Error( szErrorMsg );
--
--        goto error;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Close the files, and then open them as regular existing files.  */
--/* -------------------------------------------------------------------- */
--    psHooks->FClose( fpSHP );
--    psHooks->FClose( fpSHX );
--
--    return( SHPOpenLL( pszLayer, "r+b", psHooks ) );
--
--error:
--    if (pszFullname) free(pszFullname);
--    if (fpSHP) psHooks->FClose( fpSHP );
--    if (fpSHX) psHooks->FClose( fpSHX );
--    return SHPLIB_NULLPTR;
--}
--
--/************************************************************************/
--/*                           _SHPSetBounds()                            */
--/*                                                                      */
--/*      Compute a bounds rectangle for a shape, and set it into the     */
--/*      indicated location in the record.                               */
--/************************************************************************/
--
--static void   _SHPSetBounds( uchar * pabyRec, SHPObject * psShape )
--
--{
--    ByteCopy( &(psShape->dfXMin), pabyRec +  0, 8 );
--    ByteCopy( &(psShape->dfYMin), pabyRec +  8, 8 );
--    ByteCopy( &(psShape->dfXMax), pabyRec + 16, 8 );
--    ByteCopy( &(psShape->dfYMax), pabyRec + 24, 8 );
--
--    if( bBigEndian )
--    {
--        SwapWord( 8, pabyRec + 0 );
--        SwapWord( 8, pabyRec + 8 );
--        SwapWord( 8, pabyRec + 16 );
--        SwapWord( 8, pabyRec + 24 );
--    }
--}
--
--/************************************************************************/
--/*                         SHPComputeExtents()                          */
--/*                                                                      */
--/*      Recompute the extents of a shape.  Automatically done by        */
--/*      SHPCreateObject().                                              */
--/************************************************************************/
--
--void SHPAPI_CALL
--SHPComputeExtents( SHPObject * psObject )
--
--{
--    int               i;
--
--/* -------------------------------------------------------------------- */
--/*      Build extents for this object.                                  */
--/* -------------------------------------------------------------------- */
--    if( psObject->nVertices > 0 )
--    {
--        psObject->dfXMin = psObject->dfXMax = psObject->padfX[0];
--        psObject->dfYMin = psObject->dfYMax = psObject->padfY[0];
--        psObject->dfZMin = psObject->dfZMax = psObject->padfZ[0];
--        psObject->dfMMin = psObject->dfMMax = psObject->padfM[0];
--    }
--
--    for( i = 0; i < psObject->nVertices; i++ )
--    {
--        psObject->dfXMin = MIN(psObject->dfXMin, psObject->padfX[i]);
--        psObject->dfYMin = MIN(psObject->dfYMin, psObject->padfY[i]);
--        psObject->dfZMin = MIN(psObject->dfZMin, psObject->padfZ[i]);
--        psObject->dfMMin = MIN(psObject->dfMMin, psObject->padfM[i]);
--
--        psObject->dfXMax = MAX(psObject->dfXMax, psObject->padfX[i]);
--        psObject->dfYMax = MAX(psObject->dfYMax, psObject->padfY[i]);
--        psObject->dfZMax = MAX(psObject->dfZMax, psObject->padfZ[i]);
--        psObject->dfMMax = MAX(psObject->dfMMax, psObject->padfM[i]);
--    }
--}
--
--/************************************************************************/
--/*                          SHPCreateObject()                           */
--/*                                                                      */
--/*      Create a shape object.  It should be freed with                 */
--/*      SHPDestroyObject().                                             */
--/************************************************************************/
--
--SHPObject SHPAPI_CALL1(*)
--SHPCreateObject( int nSHPType, int nShapeId, int nParts,
--                 const int * panPartStart, const int * panPartType,
--                 int nVertices, const double *padfX, const double *padfY,
--                 const double * padfZ, const double * padfM )
--
--{
--    SHPObject *psObject;
--    int               i, bHasM, bHasZ;
--
--    psObject = STATIC_CAST(SHPObject *, calloc(1,sizeof(SHPObject)));
--    psObject->nSHPType = nSHPType;
--    psObject->nShapeId = nShapeId;
--    psObject->bMeasureIsUsed = FALSE;
--
--/* -------------------------------------------------------------------- */
--/*    Establish whether this shape type has M, and Z values.          */
--/* -------------------------------------------------------------------- */
--    if( nSHPType == SHPT_ARCM
--        || nSHPType == SHPT_POINTM
--        || nSHPType == SHPT_POLYGONM
--        || nSHPType == SHPT_MULTIPOINTM )
--    {
--        bHasM = TRUE;
--        bHasZ = FALSE;
--    }
--    else if( nSHPType == SHPT_ARCZ
--             || nSHPType == SHPT_POINTZ
--             || nSHPType == SHPT_POLYGONZ
--             || nSHPType == SHPT_MULTIPOINTZ
--             || nSHPType == SHPT_MULTIPATCH )
--    {
--        bHasM = TRUE;
--        bHasZ = TRUE;
--    }
--    else
--    {
--        bHasM = FALSE;
--        bHasZ = FALSE;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Capture parts.  Note that part type is optional, and            */
--/*      defaults to ring.                                               */
--/* -------------------------------------------------------------------- */
--    if( nSHPType == SHPT_ARC || nSHPType == SHPT_POLYGON
--        || nSHPType == SHPT_ARCM || nSHPType == SHPT_POLYGONM
--        || nSHPType == SHPT_ARCZ || nSHPType == SHPT_POLYGONZ
--        || nSHPType == SHPT_MULTIPATCH )
--    {
--        psObject->nParts = MAX(1,nParts);
--
--        psObject->panPartStart = STATIC_CAST(int *,
--            calloc(sizeof(int), psObject->nParts));
--        psObject->panPartType = STATIC_CAST(int *,
--            malloc(sizeof(int) * psObject->nParts));
--
--        psObject->panPartStart[0] = 0;
--        psObject->panPartType[0] = SHPP_RING;
--
--        for( i = 0; i < nParts; i++ )
--        {
--            if( panPartStart != SHPLIB_NULLPTR )
--                psObject->panPartStart[i] = panPartStart[i];
--
--            if( panPartType != SHPLIB_NULLPTR )
--                psObject->panPartType[i] = panPartType[i];
--            else
--                psObject->panPartType[i] = SHPP_RING;
--        }
--
--        if( psObject->panPartStart[0] != 0 )
--            psObject->panPartStart[0] = 0;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Capture vertices.  Note that X, Y, Z and M are optional.        */
--/* -------------------------------------------------------------------- */
--    if( nVertices > 0 )
--    {
--        size_t nSize = sizeof(double) * nVertices;
--        psObject->padfX = STATIC_CAST(double *, padfX ? malloc(nSize) :
--                                             calloc(sizeof(double),nVertices));
--        psObject->padfY = STATIC_CAST(double *, padfY ? malloc(nSize) :
--                                             calloc(sizeof(double),nVertices));
--        psObject->padfZ = STATIC_CAST(double *, padfZ && bHasZ ? malloc(nSize) :
--                                             calloc(sizeof(double),nVertices));
--        psObject->padfM = STATIC_CAST(double *, padfM && bHasM ? malloc(nSize) :
--                                             calloc(sizeof(double),nVertices));
--        if( padfX != SHPLIB_NULLPTR )
--            memcpy(psObject->padfX, padfX, nSize);
--        if( padfY != SHPLIB_NULLPTR )
--            memcpy(psObject->padfY, padfY, nSize);
--        if( padfZ != SHPLIB_NULLPTR && bHasZ )
--            memcpy(psObject->padfZ, padfZ, nSize);
--        if( padfM != SHPLIB_NULLPTR && bHasM )
--        {
--            memcpy(psObject->padfM, padfM, nSize);
--            psObject->bMeasureIsUsed = TRUE;
--        }
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Compute the extents.                                            */
--/* -------------------------------------------------------------------- */
--    psObject->nVertices = nVertices;
--    SHPComputeExtents( psObject );
--
--    return( psObject );
--}
--
--/************************************************************************/
--/*                       SHPCreateSimpleObject()                        */
--/*                                                                      */
--/*      Create a simple (common) shape object.  Destroy with            */
--/*      SHPDestroyObject().                                             */
--/************************************************************************/
--
--SHPObject SHPAPI_CALL1(*)
--SHPCreateSimpleObject( int nSHPType, int nVertices,
--                       const double * padfX, const double * padfY,
--                       const double * padfZ )
--
--{
--    return( SHPCreateObject( nSHPType, -1, 0, SHPLIB_NULLPTR, SHPLIB_NULLPTR,
--                             nVertices, padfX, padfY, padfZ, SHPLIB_NULLPTR ) );
--}
--
--/************************************************************************/
--/*                           SHPWriteObject()                           */
--/*                                                                      */
--/*      Write out the vertices of a new structure.  Note that it is     */
--/*      only possible to write vertices at the end of the file.         */
--/************************************************************************/
--
--int SHPAPI_CALL
--SHPWriteObject(SHPHandle psSHP, int nShapeId, SHPObject * psObject )
--
--{
--    unsigned int              nRecordOffset, nRecordSize=0;
--    int i;
--    uchar     *pabyRec;
--    int32     i32;
--    int     bAppendToLastRecord = FALSE;
--    int     bAppendToFile = FALSE;
--
--    psSHP->bUpdated = TRUE;
--
--/* -------------------------------------------------------------------- */
--/*      Ensure that shape object matches the type of the file it is     */
--/*      being written to.                                               */
--/* -------------------------------------------------------------------- */
--    assert( psObject->nSHPType == psSHP->nShapeType
--            || psObject->nSHPType == SHPT_NULL );
--
--/* -------------------------------------------------------------------- */
--/*      Ensure that -1 is used for appends.  Either blow an             */
--/*      assertion, or if they are disabled, set the shapeid to -1       */
--/*      for appends.                                                    */
--/* -------------------------------------------------------------------- */
--    assert( nShapeId == -1
--            || (nShapeId >= 0 && nShapeId < psSHP->nRecords) );
--
--    if( nShapeId != -1 && nShapeId >= psSHP->nRecords )
--        nShapeId = -1;
--
--/* -------------------------------------------------------------------- */
--/*      Add the new entity to the in memory index.                      */
--/* -------------------------------------------------------------------- */
--    if( nShapeId == -1 && psSHP->nRecords+1 > psSHP->nMaxRecords )
--    {
--        int nNewMaxRecords = psSHP->nMaxRecords + psSHP->nMaxRecords / 3 + 100;
--        unsigned int* panRecOffsetNew;
--        unsigned int* panRecSizeNew;
--
--        panRecOffsetNew = STATIC_CAST(unsigned int *,
--            SfRealloc(psSHP->panRecOffset,sizeof(unsigned int) * nNewMaxRecords ));
--        if( panRecOffsetNew == SHPLIB_NULLPTR )
--            return -1;
--        psSHP->panRecOffset = panRecOffsetNew;
--
--        panRecSizeNew = STATIC_CAST(unsigned int *,
--            SfRealloc(psSHP->panRecSize,sizeof(unsigned int) * nNewMaxRecords ));
--        if( panRecSizeNew == SHPLIB_NULLPTR )
--            return -1;
--        psSHP->panRecSize = panRecSizeNew;
--
--        psSHP->nMaxRecords = nNewMaxRecords;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Initialize record.                                              */
--/* -------------------------------------------------------------------- */
--    pabyRec = STATIC_CAST(uchar *, malloc(psObject->nVertices * 4 * sizeof(double)
--                               + psObject->nParts * 8 + 128));
--    if( pabyRec == SHPLIB_NULLPTR )
--        return -1;
--
--/* -------------------------------------------------------------------- */
--/*  Extract vertices for a Polygon or Arc.                            */
--/* -------------------------------------------------------------------- */
--    if( psObject->nSHPType == SHPT_POLYGON
--        || psObject->nSHPType == SHPT_POLYGONZ
--        || psObject->nSHPType == SHPT_POLYGONM
--        || psObject->nSHPType == SHPT_ARC
--        || psObject->nSHPType == SHPT_ARCZ
--        || psObject->nSHPType == SHPT_ARCM
--        || psObject->nSHPType == SHPT_MULTIPATCH )
--    {
--        int32         nPoints, nParts;
--
--        nPoints = psObject->nVertices;
--        nParts = psObject->nParts;
--
--        _SHPSetBounds( pabyRec + 12, psObject );
--
--        if( bBigEndian ) SwapWord( 4, &nPoints );
--        if( bBigEndian ) SwapWord( 4, &nParts );
--
--        ByteCopy( &nPoints, pabyRec + 40 + 8, 4 );
--        ByteCopy( &nParts, pabyRec + 36 + 8, 4 );
--
--        nRecordSize = 52;
--
--        /*
--         * Write part start positions.
--         */
--        ByteCopy( psObject->panPartStart, pabyRec + 44 + 8,
--                  4 * psObject->nParts );
--        for( i = 0; i < psObject->nParts; i++ )
--        {
--            if( bBigEndian ) SwapWord( 4, pabyRec + 44 + 8 + 4*i );
--            nRecordSize += 4;
--        }
--
--        /*
--         * Write multipatch part types if needed.
--         */
--        if( psObject->nSHPType == SHPT_MULTIPATCH )
--        {
--            memcpy( pabyRec + nRecordSize, psObject->panPartType,
--                    4*psObject->nParts );
--            for( i = 0; i < psObject->nParts; i++ )
--            {
--                if( bBigEndian ) SwapWord( 4, pabyRec + nRecordSize );
--                nRecordSize += 4;
--            }
--        }
--
--        /*
--         * Write the (x,y) vertex values.
--         */
--        for( i = 0; i < psObject->nVertices; i++ )
--        {
--            ByteCopy( psObject->padfX + i, pabyRec + nRecordSize, 8 );
--            ByteCopy( psObject->padfY + i, pabyRec + nRecordSize + 8, 8 );
--
--            if( bBigEndian )
--                SwapWord( 8, pabyRec + nRecordSize );
--
--            if( bBigEndian )
--                SwapWord( 8, pabyRec + nRecordSize + 8 );
--
--            nRecordSize += 2 * 8;
--        }
--
--        /*
--         * Write the Z coordinates (if any).
--         */
--        if( psObject->nSHPType == SHPT_POLYGONZ
--            || psObject->nSHPType == SHPT_ARCZ
--            || psObject->nSHPType == SHPT_MULTIPATCH )
--        {
--            ByteCopy( &(psObject->dfZMin), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            ByteCopy( &(psObject->dfZMax), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            for( i = 0; i < psObject->nVertices; i++ )
--            {
--                ByteCopy( psObject->padfZ + i, pabyRec + nRecordSize, 8 );
--                if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--                nRecordSize += 8;
--            }
--        }
--
--        /*
--         * Write the M values, if any.
--         */
--        if( psObject->bMeasureIsUsed
--            && (psObject->nSHPType == SHPT_POLYGONM
--                || psObject->nSHPType == SHPT_ARCM
--#ifndef DISABLE_MULTIPATCH_MEASURE
--                || psObject->nSHPType == SHPT_MULTIPATCH
--#endif
--                || psObject->nSHPType == SHPT_POLYGONZ
--                || psObject->nSHPType == SHPT_ARCZ) )
--        {
--            ByteCopy( &(psObject->dfMMin), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            ByteCopy( &(psObject->dfMMax), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            for( i = 0; i < psObject->nVertices; i++ )
--            {
--                ByteCopy( psObject->padfM + i, pabyRec + nRecordSize, 8 );
--                if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--                nRecordSize += 8;
--            }
--        }
--    }
--
--/* -------------------------------------------------------------------- */
--/*  Extract vertices for a MultiPoint.                                        */
--/* -------------------------------------------------------------------- */
--    else if( psObject->nSHPType == SHPT_MULTIPOINT
--             || psObject->nSHPType == SHPT_MULTIPOINTZ
--             || psObject->nSHPType == SHPT_MULTIPOINTM )
--    {
--        int32         nPoints;
--
--        nPoints = psObject->nVertices;
--
--        _SHPSetBounds( pabyRec + 12, psObject );
--
--        if( bBigEndian ) SwapWord( 4, &nPoints );
--        ByteCopy( &nPoints, pabyRec + 44, 4 );
--
--        for( i = 0; i < psObject->nVertices; i++ )
--        {
--            ByteCopy( psObject->padfX + i, pabyRec + 48 + i*16, 8 );
--            ByteCopy( psObject->padfY + i, pabyRec + 48 + i*16 + 8, 8 );
--
--            if( bBigEndian ) SwapWord( 8, pabyRec + 48 + i*16 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + 48 + i*16 + 8 );
--        }
--
--        nRecordSize = 48 + 16 * psObject->nVertices;
--
--        if( psObject->nSHPType == SHPT_MULTIPOINTZ )
--        {
--            ByteCopy( &(psObject->dfZMin), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            ByteCopy( &(psObject->dfZMax), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            for( i = 0; i < psObject->nVertices; i++ )
--            {
--                ByteCopy( psObject->padfZ + i, pabyRec + nRecordSize, 8 );
--                if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--                nRecordSize += 8;
--            }
--        }
--
--        if( psObject->bMeasureIsUsed
--            && (psObject->nSHPType == SHPT_MULTIPOINTZ
--                || psObject->nSHPType == SHPT_MULTIPOINTM) )
--        {
--            ByteCopy( &(psObject->dfMMin), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            ByteCopy( &(psObject->dfMMax), pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--
--            for( i = 0; i < psObject->nVertices; i++ )
--            {
--                ByteCopy( psObject->padfM + i, pabyRec + nRecordSize, 8 );
--                if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--                nRecordSize += 8;
--            }
--        }
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Write point.                                                  */
--/* -------------------------------------------------------------------- */
--    else if( psObject->nSHPType == SHPT_POINT
--             || psObject->nSHPType == SHPT_POINTZ
--             || psObject->nSHPType == SHPT_POINTM )
--    {
--        ByteCopy( psObject->padfX, pabyRec + 12, 8 );
--        ByteCopy( psObject->padfY, pabyRec + 20, 8 );
--
--        if( bBigEndian ) SwapWord( 8, pabyRec + 12 );
--        if( bBigEndian ) SwapWord( 8, pabyRec + 20 );
--
--        nRecordSize = 28;
--
--        if( psObject->nSHPType == SHPT_POINTZ )
--        {
--            ByteCopy( psObject->padfZ, pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--        }
--
--        if( psObject->bMeasureIsUsed
--            && (psObject->nSHPType == SHPT_POINTZ
--                || psObject->nSHPType == SHPT_POINTM) )
--        {
--            ByteCopy( psObject->padfM, pabyRec + nRecordSize, 8 );
--            if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
--            nRecordSize += 8;
--        }
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Not much to do for null geometries.                             */
--/* -------------------------------------------------------------------- */
--    else if( psObject->nSHPType == SHPT_NULL )
--    {
--        nRecordSize = 12;
--    }
--
--    else
--    {
--        /* unknown type */
--        assert( FALSE );
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Establish where we are going to put this record. If we are      */
--/*      rewriting the last record of the file, then we can update it in */
--/*      place. Otherwise if rewriting an existing record, and it will   */
--/*      fit, then put it  back where the original came from.  Otherwise */
--/*      write at the end.                                               */
--/* -------------------------------------------------------------------- */
--    if( nShapeId != -1 && psSHP->panRecOffset[nShapeId] +
--                        psSHP->panRecSize[nShapeId] + 8 == psSHP->nFileSize )
--    {
--        nRecordOffset = psSHP->panRecOffset[nShapeId];
--        bAppendToLastRecord = TRUE;
--    }
--    else if( nShapeId == -1 || psSHP->panRecSize[nShapeId] < nRecordSize-8 )
--    {
--        if( psSHP->nFileSize > UINT_MAX - nRecordSize)
--        {
--            char str[128];
--            snprintf( str, sizeof(str), "Failed to write shape object. "
--                     "File size cannot reach %u + %u.",
--                     psSHP->nFileSize, nRecordSize );
--            str[sizeof(str)-1] = '\0';
--            psSHP->sHooks.Error( str );
--            free( pabyRec );
--            return -1;
--        }
--
--        bAppendToFile = TRUE;
--        nRecordOffset = psSHP->nFileSize;
--    }
--    else
--    {
--        nRecordOffset = psSHP->panRecOffset[nShapeId];
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Set the shape type, record number, and record size.             */
--/* -------------------------------------------------------------------- */
--    i32 = (nShapeId < 0) ? psSHP->nRecords+1 : nShapeId+1;                                    /* record # */
--    if( !bBigEndian ) SwapWord( 4, &i32 );
--    ByteCopy( &i32, pabyRec, 4 );
--
--    i32 = (nRecordSize-8)/2;                          /* record size */
--    if( !bBigEndian ) SwapWord( 4, &i32 );
--    ByteCopy( &i32, pabyRec + 4, 4 );
--
--    i32 = psObject->nSHPType;                         /* shape type */
--    if( bBigEndian ) SwapWord( 4, &i32 );
--    ByteCopy( &i32, pabyRec + 8, 4 );
--
--/* -------------------------------------------------------------------- */
--/*      Write out record.                                               */
--/* -------------------------------------------------------------------- */
--    if( psSHP->sHooks.FSeek( psSHP->fpSHP, nRecordOffset, 0 ) != 0 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Error in psSHP->sHooks.FSeek() while writing object to .shp file: %s",
--                  strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--
--        free( pabyRec );
--        return -1;
--    }
--    if( psSHP->sHooks.FWrite( pabyRec, nRecordSize, 1, psSHP->fpSHP ) < 1 )
--    {
--        char szErrorMsg[200];
--
--        snprintf( szErrorMsg, sizeof(szErrorMsg),
--                 "Error in psSHP->sHooks.FWrite() while writing object of %u bytes to .shp file: %s",
--                  nRecordSize, strerror(errno) );
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--
--        free( pabyRec );
--        return -1;
--    }
--
--    free( pabyRec );
--
--    if( bAppendToLastRecord )
--    {
--        psSHP->nFileSize = psSHP->panRecOffset[nShapeId] + nRecordSize; 
--    }
--    else if( bAppendToFile )
--    {
--        if( nShapeId == -1 )
--            nShapeId = psSHP->nRecords++;
--
--        psSHP->panRecOffset[nShapeId] = psSHP->nFileSize;
--        psSHP->nFileSize += nRecordSize;
--    }
--    psSHP->panRecSize[nShapeId] = nRecordSize-8;
--
--/* -------------------------------------------------------------------- */
--/*    Expand file wide bounds based on this shape.                    */
--/* -------------------------------------------------------------------- */
--    if( psSHP->adBoundsMin[0] == 0.0
--        && psSHP->adBoundsMax[0] == 0.0
--        && psSHP->adBoundsMin[1] == 0.0
--        && psSHP->adBoundsMax[1] == 0.0 )
--    {
--        if( psObject->nSHPType == SHPT_NULL || psObject->nVertices == 0 )
--        {
--            psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = 0.0;
--            psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = 0.0;
--            psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = 0.0;
--            psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = 0.0;
--        }
--        else
--        {
--            psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = psObject->padfX[0];
--            psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = psObject->padfY[0];
--            psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = psObject->padfZ ? psObject->padfZ[0] : 0.0;
--            psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = psObject->padfM ? psObject->padfM[0] : 0.0;
--        }
--    }
--
--    for( i = 0; i < psObject->nVertices; i++ )
--    {
--        psSHP->adBoundsMin[0] = MIN(psSHP->adBoundsMin[0],psObject->padfX[i]);
--        psSHP->adBoundsMin[1] = MIN(psSHP->adBoundsMin[1],psObject->padfY[i]);
--        psSHP->adBoundsMax[0] = MAX(psSHP->adBoundsMax[0],psObject->padfX[i]);
--        psSHP->adBoundsMax[1] = MAX(psSHP->adBoundsMax[1],psObject->padfY[i]);
--        if( psObject->padfZ )
--        {
--            psSHP->adBoundsMin[2] = MIN(psSHP->adBoundsMin[2],psObject->padfZ[i]);
--            psSHP->adBoundsMax[2] = MAX(psSHP->adBoundsMax[2],psObject->padfZ[i]);
--        }
--        if( psObject->padfM )
--        {
--            psSHP->adBoundsMin[3] = MIN(psSHP->adBoundsMin[3],psObject->padfM[i]);
--            psSHP->adBoundsMax[3] = MAX(psSHP->adBoundsMax[3],psObject->padfM[i]);
--        }
--    }
--
--    return( nShapeId  );
--}
--
--/************************************************************************/
--/*                         SHPAllocBuffer()                             */
--/************************************************************************/
--
--static void* SHPAllocBuffer(unsigned char** pBuffer, int nSize)
--{
--    unsigned char* pRet;
--
--    if( pBuffer == SHPLIB_NULLPTR )
--        return calloc(1, nSize);
--
--    pRet = *pBuffer;
--    if( pRet == SHPLIB_NULLPTR )
--        return SHPLIB_NULLPTR;
--
--    (*pBuffer) += nSize;
--    return pRet;
--}
--
--/************************************************************************/
--/*                    SHPReallocObjectBufIfNecessary()                  */
--/************************************************************************/
--
--static unsigned char* SHPReallocObjectBufIfNecessary ( SHPHandle psSHP,
--                                                       int nObjectBufSize )
--{
--    unsigned char* pBuffer;
--    if( nObjectBufSize == 0 )
--    {
--        nObjectBufSize = 4 * sizeof(double);
--    }
--    if( nObjectBufSize > psSHP->nObjectBufSize )
--    {
--        pBuffer = STATIC_CAST(unsigned char*, realloc( psSHP->pabyObjectBuf, nObjectBufSize ));
--        if( pBuffer != SHPLIB_NULLPTR )
--        {
--            psSHP->pabyObjectBuf = pBuffer;
--            psSHP->nObjectBufSize = nObjectBufSize;
--        }
--    }
--    else
--        pBuffer = psSHP->pabyObjectBuf;
--    return pBuffer;
--}
--
--/************************************************************************/
--/*                          SHPReadObject()                             */
--/*                                                                      */
--/*      Read the vertices, parts, and other non-attribute information */
--/*    for one shape.                                                  */
--/************************************************************************/
--
--SHPObject SHPAPI_CALL1(*)
--SHPReadObject( SHPHandle psSHP, int hEntity )
--
--{
--    int                  nEntitySize, nRequiredSize;
--    SHPObject           *psShape;
--    char                 szErrorMsg[128];
--    int                  nSHPType;
--    int                  nBytesRead;
--
--/* -------------------------------------------------------------------- */
--/*      Validate the record/entity number.                              */
--/* -------------------------------------------------------------------- */
--    if( hEntity < 0 || hEntity >= psSHP->nRecords )
--        return SHPLIB_NULLPTR;
--
--/* -------------------------------------------------------------------- */
--/*      Read offset/length from SHX loading if necessary.               */
--/* -------------------------------------------------------------------- */
--    if( psSHP->panRecOffset[hEntity] == 0 && psSHP->fpSHX != SHPLIB_NULLPTR )
--    {
--        unsigned int       nOffset, nLength;
--
--        if( psSHP->sHooks.FSeek( psSHP->fpSHX, 100 + 8 * hEntity, 0 ) != 0 ||
--            psSHP->sHooks.FRead( &nOffset, 1, 4, psSHP->fpSHX ) != 4 ||
--            psSHP->sHooks.FRead( &nLength, 1, 4, psSHP->fpSHX ) != 4 )
--        {
--            char str[128];
--            snprintf( str, sizeof(str),
--                    "Error in fseek()/fread() reading object from .shx file at offset %d",
--                    100 + 8 * hEntity);
--            str[sizeof(str)-1] = '\0';
--
--            psSHP->sHooks.Error( str );
--            return SHPLIB_NULLPTR;
--        }
--        if( !bBigEndian ) SwapWord( 4, &nOffset );
--        if( !bBigEndian ) SwapWord( 4, &nLength );
--
--        if( nOffset > STATIC_CAST(unsigned int, INT_MAX) )
--        {
--            char str[128];
--            snprintf( str, sizeof(str),
--                    "Invalid offset for entity %d", hEntity);
--            str[sizeof(str)-1] = '\0';
--
--            psSHP->sHooks.Error( str );
--            return SHPLIB_NULLPTR;
--        }
--        if( nLength > STATIC_CAST(unsigned int, INT_MAX / 2 - 4) )
--        {
--            char str[128];
--            snprintf( str, sizeof(str),
--                    "Invalid length for entity %d", hEntity);
--            str[sizeof(str)-1] = '\0';
--
--            psSHP->sHooks.Error( str );
--            return SHPLIB_NULLPTR;
--        }
--
--        psSHP->panRecOffset[hEntity] = nOffset*2;
--        psSHP->panRecSize[hEntity] = nLength*2;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Ensure our record buffer is large enough.                       */
--/* -------------------------------------------------------------------- */
--    nEntitySize = psSHP->panRecSize[hEntity]+8;
--    if( nEntitySize > psSHP->nBufSize )
--    {
--        uchar* pabyRecNew;
--        int nNewBufSize = nEntitySize;
--        if( nNewBufSize < INT_MAX - nNewBufSize / 3 )
--            nNewBufSize += nNewBufSize / 3;
--        else
--            nNewBufSize = INT_MAX;
--
--        /* Before allocating too much memory, check that the file is big enough */
--        /* and do not trust the file size in the header the first time we */
--        /* need to allocate more than 10 MB */
--        if( nNewBufSize >= 10 * 1024 * 1024 )
--        {
--            if( psSHP->nBufSize < 10 * 1024 * 1024 )
--            {
--                SAOffset nFileSize;
--                psSHP->sHooks.FSeek( psSHP->fpSHP, 0, 2 );
--                nFileSize = psSHP->sHooks.FTell(psSHP->fpSHP);
--                if( nFileSize >= UINT_MAX )
--                    psSHP->nFileSize = UINT_MAX;
--                else
--                    psSHP->nFileSize = STATIC_CAST(unsigned int, nFileSize);
--            }
--
--            if( psSHP->panRecOffset[hEntity] >= psSHP->nFileSize ||
--                /* We should normally use nEntitySize instead of*/
--                /* psSHP->panRecSize[hEntity] in the below test, but because of */
--                /* the case of non conformant .shx files detailed a bit below, */
--                /* let be more tolerant */
--                psSHP->panRecSize[hEntity] > psSHP->nFileSize - psSHP->panRecOffset[hEntity] )
--            {
--                char str[128];
--                snprintf( str, sizeof(str),
--                            "Error in fread() reading object of size %d at offset %u from .shp file",
--                            nEntitySize, psSHP->panRecOffset[hEntity] );
--                str[sizeof(str)-1] = '\0';
--
--                psSHP->sHooks.Error( str );
--                return SHPLIB_NULLPTR;
--            }
--        }
--
--        pabyRecNew = STATIC_CAST(uchar *, SfRealloc(psSHP->pabyRec,nNewBufSize));
--        if (pabyRecNew == SHPLIB_NULLPTR)
--        {
--            snprintf( szErrorMsg, sizeof(szErrorMsg),
--                     "Not enough memory to allocate requested memory (nNewBufSize=%d). "
--                     "Probably broken SHP file", nNewBufSize);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            return SHPLIB_NULLPTR;
--        }
--
--        /* Only set new buffer size after successful alloc */
--        psSHP->pabyRec = pabyRecNew;
--        psSHP->nBufSize = nNewBufSize;
--    }
--
--    /* In case we were not able to reallocate the buffer on a previous step */
--    if (psSHP->pabyRec == SHPLIB_NULLPTR)
--    {
--        return SHPLIB_NULLPTR;
--    }
--
--/* -------------------------------------------------------------------- */
--/*      Read the record.                                                */
--/* -------------------------------------------------------------------- */
--    if( psSHP->sHooks.FSeek( psSHP->fpSHP, psSHP->panRecOffset[hEntity], 0 ) != 0 )
--    {
--        /*
--         * TODO - mloskot: Consider detailed diagnostics of shape file,
--         * for example to detect if file is truncated.
--         */
--        char str[128];
--        snprintf( str, sizeof(str),
--                 "Error in fseek() reading object from .shp file at offset %u",
--                 psSHP->panRecOffset[hEntity]);
--        str[sizeof(str)-1] = '\0';
--
--        psSHP->sHooks.Error( str );
--        return SHPLIB_NULLPTR;
--    }
--
--    nBytesRead = STATIC_CAST(int, psSHP->sHooks.FRead( psSHP->pabyRec, 1, nEntitySize, psSHP->fpSHP ));
--
--    /* Special case for a shapefile whose .shx content length field is not equal */
--    /* to the content length field of the .shp, which is a violation of "The */
--    /* content length stored in the index record is the same as the value stored in the main */
--    /* file record header." (http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf, page 24) */
--    /* Actually in that case the .shx content length is equal to the .shp content length + */
--    /* 4 (16 bit words), representing the 8 bytes of the record header... */
--    if( nBytesRead >= 8 && nBytesRead == nEntitySize - 8 )
--    {
--        /* Do a sanity check */
--        int nSHPContentLength;
--        memcpy( &nSHPContentLength, psSHP->pabyRec + 4, 4 );
--        if( !bBigEndian ) SwapWord( 4, &(nSHPContentLength) );
--        if( nSHPContentLength < 0 ||
--            nSHPContentLength > INT_MAX / 2 - 4 ||
--            2 * nSHPContentLength + 8 != nBytesRead )
--        {
--            char str[128];
--            snprintf( str, sizeof(str),
--                    "Sanity check failed when trying to recover from inconsistent .shx/.shp with shape %d",
--                    hEntity );
--            str[sizeof(str)-1] = '\0';
--
--            psSHP->sHooks.Error( str );
--            return SHPLIB_NULLPTR;
--        }
--    }
--    else if( nBytesRead != nEntitySize )
--    {
--        /*
--         * TODO - mloskot: Consider detailed diagnostics of shape file,
--         * for example to detect if file is truncated.
--         */
--        char str[128];
--        snprintf( str, sizeof(str),
--                 "Error in fread() reading object of size %d at offset %u from .shp file",
--                 nEntitySize, psSHP->panRecOffset[hEntity] );
--        str[sizeof(str)-1] = '\0';
--
--        psSHP->sHooks.Error( str );
--        return SHPLIB_NULLPTR;
--    }
--
--    if ( 8 + 4 > nEntitySize )
--    {
--        snprintf(szErrorMsg, sizeof(szErrorMsg),
--                 "Corrupted .shp file : shape %d : nEntitySize = %d",
--                 hEntity, nEntitySize);
--        szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--        psSHP->sHooks.Error( szErrorMsg );
--        return SHPLIB_NULLPTR;
--    }
--    memcpy( &nSHPType, psSHP->pabyRec + 8, 4 );
--
--    if( bBigEndian ) SwapWord( 4, &(nSHPType) );
--
--/* -------------------------------------------------------------------- */
--/*    Allocate and minimally initialize the object.                   */
--/* -------------------------------------------------------------------- */
--    if( psSHP->bFastModeReadObject )
--    {
--        if( psSHP->psCachedObject->bFastModeReadObject )
--        {
--            psSHP->sHooks.Error( "Invalid read pattern in fast read mode. "
--                                 "SHPDestroyObject() should be called." );
--            return SHPLIB_NULLPTR;
--        }
--
--        psShape = psSHP->psCachedObject;
--        memset(psShape, 0, sizeof(SHPObject));
--    }
--    else
--        psShape = STATIC_CAST(SHPObject *, calloc(1,sizeof(SHPObject)));
--    psShape->nShapeId = hEntity;
--    psShape->nSHPType = nSHPType;
--    psShape->bMeasureIsUsed = FALSE;
--    psShape->bFastModeReadObject = psSHP->bFastModeReadObject;
--
--/* ==================================================================== */
--/*  Extract vertices for a Polygon or Arc.                            */
--/* ==================================================================== */
--    if( psShape->nSHPType == SHPT_POLYGON || psShape->nSHPType == SHPT_ARC
--        || psShape->nSHPType == SHPT_POLYGONZ
--        || psShape->nSHPType == SHPT_POLYGONM
--        || psShape->nSHPType == SHPT_ARCZ
--        || psShape->nSHPType == SHPT_ARCM
--        || psShape->nSHPType == SHPT_MULTIPATCH )
--    {
--        int32         nPoints, nParts;
--        int                   i, nOffset;
--        unsigned char* pBuffer = SHPLIB_NULLPTR;
--        unsigned char** ppBuffer = SHPLIB_NULLPTR;
--
--        if ( 40 + 8 + 4 > nEntitySize )
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d : nEntitySize = %d",
--                     hEntity, nEntitySize);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--/* -------------------------------------------------------------------- */
--/*    Get the X/Y bounds.                                             */
--/* -------------------------------------------------------------------- */
--        memcpy( &(psShape->dfXMin), psSHP->pabyRec + 8 +  4, 8 );
--        memcpy( &(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8 );
--        memcpy( &(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8 );
--        memcpy( &(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8 );
--
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfXMin) );
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfYMin) );
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfXMax) );
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfYMax) );
--
--/* -------------------------------------------------------------------- */
--/*      Extract part/point count, and build vertex and part arrays      */
--/*      to proper size.                                                 */
--/* -------------------------------------------------------------------- */
--        memcpy( &nPoints, psSHP->pabyRec + 40 + 8, 4 );
--        memcpy( &nParts, psSHP->pabyRec + 36 + 8, 4 );
--
--        if( bBigEndian ) SwapWord( 4, &nPoints );
--        if( bBigEndian ) SwapWord( 4, &nParts );
--
--        /* nPoints and nParts are unsigned */
--        if (/* nPoints < 0 || nParts < 0 || */
--            nPoints > 50 * 1000 * 1000 || nParts > 10 * 1000 * 1000)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d, nPoints=%u, nParts=%u.",
--                     hEntity, nPoints, nParts);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--
--        /* With the previous checks on nPoints and nParts, */
--        /* we should not overflow here and after */
--        /* since 50 M * (16 + 8 + 8) = 1 600 MB */
--        nRequiredSize = 44 + 8 + 4 * nParts + 16 * nPoints;
--        if ( psShape->nSHPType == SHPT_POLYGONZ
--             || psShape->nSHPType == SHPT_ARCZ
--             || psShape->nSHPType == SHPT_MULTIPATCH )
--        {
--            nRequiredSize += 16 + 8 * nPoints;
--        }
--        if( psShape->nSHPType == SHPT_MULTIPATCH )
--        {
--            nRequiredSize += 4 * nParts;
--        }
--        if (nRequiredSize > nEntitySize)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d, nPoints=%u, nParts=%u, nEntitySize=%d.",
--                     hEntity, nPoints, nParts, nEntitySize);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--
--        if( psShape->bFastModeReadObject )
--        {
--            int nObjectBufSize = 4 * sizeof(double) * nPoints + 2 * sizeof(int) * nParts;
--            pBuffer = SHPReallocObjectBufIfNecessary(psSHP, nObjectBufSize);
--            ppBuffer = &pBuffer;
--        }
--
--        psShape->nVertices = nPoints;
--        psShape->padfX = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--        psShape->padfY = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--        psShape->padfZ = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--        psShape->padfM = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--
--        psShape->nParts = nParts;
--        psShape->panPartStart = STATIC_CAST(int *, SHPAllocBuffer(ppBuffer, nParts * sizeof(int)));
--        psShape->panPartType = STATIC_CAST(int *, SHPAllocBuffer(ppBuffer, nParts * sizeof(int)));
--
--        if (psShape->padfX == SHPLIB_NULLPTR ||
--            psShape->padfY == SHPLIB_NULLPTR ||
--            psShape->padfZ == SHPLIB_NULLPTR ||
--            psShape->padfM == SHPLIB_NULLPTR ||
--            psShape->panPartStart == SHPLIB_NULLPTR ||
--            psShape->panPartType == SHPLIB_NULLPTR)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                    "Not enough memory to allocate requested memory (nPoints=%u, nParts=%u) for shape %d. "
--                    "Probably broken SHP file", nPoints, nParts, hEntity );
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--
--        for( i = 0; STATIC_CAST(int32, i) < nParts; i++ )
--            psShape->panPartType[i] = SHPP_RING;
--
--/* -------------------------------------------------------------------- */
--/*      Copy out the part array from the record.                        */
--/* -------------------------------------------------------------------- */
--        memcpy( psShape->panPartStart, psSHP->pabyRec + 44 + 8, 4 * nParts );
--        for( i = 0; STATIC_CAST(int32, i) < nParts; i++ )
--        {
--            if( bBigEndian ) SwapWord( 4, psShape->panPartStart+i );
--
--            /* We check that the offset is inside the vertex array */
--            if (psShape->panPartStart[i] < 0
--                || (psShape->panPartStart[i] >= psShape->nVertices
--                    && psShape->nVertices > 0)
--                || (psShape->panPartStart[i] > 0 && psShape->nVertices == 0) )
--            {
--                snprintf(szErrorMsg, sizeof(szErrorMsg),
--                         "Corrupted .shp file : shape %d : panPartStart[%d] = %d, nVertices = %d",
--                         hEntity, i, psShape->panPartStart[i], psShape->nVertices);
--                szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--                psSHP->sHooks.Error( szErrorMsg );
--                SHPDestroyObject(psShape);
--                return SHPLIB_NULLPTR;
--            }
--            if (i > 0 && psShape->panPartStart[i] <= psShape->panPartStart[i-1])
--            {
--                snprintf(szErrorMsg, sizeof(szErrorMsg),
--                         "Corrupted .shp file : shape %d : panPartStart[%d] = %d, panPartStart[%d] = %d",
--                         hEntity, i, psShape->panPartStart[i], i - 1, psShape->panPartStart[i - 1]);
--                szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--                psSHP->sHooks.Error( szErrorMsg );
--                SHPDestroyObject(psShape);
--                return SHPLIB_NULLPTR;
--            }
--        }
--
--        nOffset = 44 + 8 + 4*nParts;
--
--/* -------------------------------------------------------------------- */
--/*      If this is a multipatch, we will also have parts types.         */
--/* -------------------------------------------------------------------- */
--        if( psShape->nSHPType == SHPT_MULTIPATCH )
--        {
--            memcpy( psShape->panPartType, psSHP->pabyRec + nOffset, 4*nParts );
--            for( i = 0; STATIC_CAST(int32, i) < nParts; i++ )
--            {
--                if( bBigEndian ) SwapWord( 4, psShape->panPartType+i );
--            }
--
--            nOffset += 4*nParts;
--        }
--
--/* -------------------------------------------------------------------- */
--/*      Copy out the vertices from the record.                          */
--/* -------------------------------------------------------------------- */
--        for( i = 0; STATIC_CAST(int32, i) < nPoints; i++ )
--        {
--            memcpy(psShape->padfX + i,
--                   psSHP->pabyRec + nOffset + i * 16,
--                   8 );
--
--            memcpy(psShape->padfY + i,
--                   psSHP->pabyRec + nOffset + i * 16 + 8,
--                   8 );
--
--            if( bBigEndian ) SwapWord( 8, psShape->padfX + i );
--            if( bBigEndian ) SwapWord( 8, psShape->padfY + i );
--        }
--
--        nOffset += 16*nPoints;
--
--/* -------------------------------------------------------------------- */
--/*      If we have a Z coordinate, collect that now.                    */
--/* -------------------------------------------------------------------- */
--        if( psShape->nSHPType == SHPT_POLYGONZ
--            || psShape->nSHPType == SHPT_ARCZ
--            || psShape->nSHPType == SHPT_MULTIPATCH )
--        {
--            memcpy( &(psShape->dfZMin), psSHP->pabyRec + nOffset, 8 );
--            memcpy( &(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8 );
--
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) );
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) );
--
--            for( i = 0; STATIC_CAST(int32, i) < nPoints; i++ )
--            {
--                memcpy( psShape->padfZ + i,
--                        psSHP->pabyRec + nOffset + 16 + i*8, 8 );
--                if( bBigEndian ) SwapWord( 8, psShape->padfZ + i );
--            }
--
--            nOffset += 16 + 8*nPoints;
--        }
--        else if( psShape->bFastModeReadObject )
--        {
--            psShape->padfZ = SHPLIB_NULLPTR;
--        }
--
--/* -------------------------------------------------------------------- */
--/*      If we have a M measure value, then read it now.  We assume      */
--/*      that the measure can be present for any shape if the size is    */
--/*      big enough, but really it will only occur for the Z shapes      */
--/*      (options), and the M shapes.                                    */
--/* -------------------------------------------------------------------- */
--        if( nEntitySize >= STATIC_CAST(int, nOffset + 16 + 8*nPoints) )
--        {
--            memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 );
--            memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 );
--
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) );
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) );
--
--            for( i = 0; STATIC_CAST(int32, i) < nPoints; i++ )
--            {
--                memcpy( psShape->padfM + i,
--                        psSHP->pabyRec + nOffset + 16 + i*8, 8 );
--                if( bBigEndian ) SwapWord( 8, psShape->padfM + i );
--            }
--            psShape->bMeasureIsUsed = TRUE;
--        }
--        else if( psShape->bFastModeReadObject )
--        {
--            psShape->padfM = SHPLIB_NULLPTR;
--        }
--    }
--
--/* ==================================================================== */
--/*  Extract vertices for a MultiPoint.                                        */
--/* ==================================================================== */
--    else if( psShape->nSHPType == SHPT_MULTIPOINT
--             || psShape->nSHPType == SHPT_MULTIPOINTM
--             || psShape->nSHPType == SHPT_MULTIPOINTZ )
--    {
--        int32         nPoints;
--        int                   i, nOffset;
--        unsigned char* pBuffer = SHPLIB_NULLPTR;
--        unsigned char** ppBuffer = SHPLIB_NULLPTR;
--
--        if ( 44 + 4 > nEntitySize )
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d : nEntitySize = %d",
--                     hEntity, nEntitySize);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--        memcpy( &nPoints, psSHP->pabyRec + 44, 4 );
--
--        if( bBigEndian ) SwapWord( 4, &nPoints );
--
--        /* nPoints is unsigned */
--        if (/* nPoints < 0 || */ nPoints > 50 * 1000 * 1000)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d : nPoints = %u",
--                     hEntity, nPoints);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--
--        nRequiredSize = 48 + nPoints * 16;
--        if( psShape->nSHPType == SHPT_MULTIPOINTZ )
--        {
--            nRequiredSize += 16 + nPoints * 8;
--        }
--        if (nRequiredSize > nEntitySize)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d : nPoints = %u, nEntitySize = %d",
--                     hEntity, nPoints, nEntitySize);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--
--        if( psShape->bFastModeReadObject )
--        {
--            int nObjectBufSize = 4 * sizeof(double) * nPoints;
--            pBuffer = SHPReallocObjectBufIfNecessary(psSHP, nObjectBufSize);
--            ppBuffer = &pBuffer;
--        }
--
--        psShape->nVertices = nPoints;
--
--        psShape->padfX = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--        psShape->padfY = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--        psShape->padfZ = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--        psShape->padfM = STATIC_CAST(double *, SHPAllocBuffer(ppBuffer, sizeof(double) * nPoints));
--
--        if (psShape->padfX == SHPLIB_NULLPTR ||
--            psShape->padfY == SHPLIB_NULLPTR ||
--            psShape->padfZ == SHPLIB_NULLPTR ||
--            psShape->padfM == SHPLIB_NULLPTR)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Not enough memory to allocate requested memory (nPoints=%u) for shape %d. "
--                     "Probably broken SHP file", nPoints, hEntity );
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--
--        for( i = 0; STATIC_CAST(int32, i) < nPoints; i++ )
--        {
--            memcpy(psShape->padfX+i, psSHP->pabyRec + 48 + 16 * i, 8 );
--            memcpy(psShape->padfY+i, psSHP->pabyRec + 48 + 16 * i + 8, 8 );
--
--            if( bBigEndian ) SwapWord( 8, psShape->padfX + i );
--            if( bBigEndian ) SwapWord( 8, psShape->padfY + i );
--        }
--
--        nOffset = 48 + 16*nPoints;
--
--/* -------------------------------------------------------------------- */
--/*    Get the X/Y bounds.                                             */
--/* -------------------------------------------------------------------- */
--        memcpy( &(psShape->dfXMin), psSHP->pabyRec + 8 +  4, 8 );
--        memcpy( &(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8 );
--        memcpy( &(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8 );
--        memcpy( &(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8 );
--
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfXMin) );
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfYMin) );
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfXMax) );
--        if( bBigEndian ) SwapWord( 8, &(psShape->dfYMax) );
--
--/* -------------------------------------------------------------------- */
--/*      If we have a Z coordinate, collect that now.                    */
--/* -------------------------------------------------------------------- */
--        if( psShape->nSHPType == SHPT_MULTIPOINTZ )
--        {
--            memcpy( &(psShape->dfZMin), psSHP->pabyRec + nOffset, 8 );
--            memcpy( &(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8 );
--
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) );
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) );
--
--            for( i = 0; STATIC_CAST(int32, i) < nPoints; i++ )
--            {
--                memcpy( psShape->padfZ + i,
--                        psSHP->pabyRec + nOffset + 16 + i*8, 8 );
--                if( bBigEndian ) SwapWord( 8, psShape->padfZ + i );
--            }
--
--            nOffset += 16 + 8*nPoints;
--        }
--        else if( psShape->bFastModeReadObject )
--            psShape->padfZ = SHPLIB_NULLPTR;
--
--/* -------------------------------------------------------------------- */
--/*      If we have a M measure value, then read it now.  We assume      */
--/*      that the measure can be present for any shape if the size is    */
--/*      big enough, but really it will only occur for the Z shapes      */
--/*      (options), and the M shapes.                                    */
--/* -------------------------------------------------------------------- */
--        if( nEntitySize >= STATIC_CAST(int, nOffset + 16 + 8*nPoints) )
--        {
--            memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 );
--            memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 );
--
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) );
--            if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) );
--
--            for( i = 0; STATIC_CAST(int32, i) < nPoints; i++ )
--            {
--                memcpy( psShape->padfM + i,
--                        psSHP->pabyRec + nOffset + 16 + i*8, 8 );
--                if( bBigEndian ) SwapWord( 8, psShape->padfM + i );
--            }
--            psShape->bMeasureIsUsed = TRUE;
--        }
--        else if( psShape->bFastModeReadObject )
--            psShape->padfM = SHPLIB_NULLPTR;
--    }
--
--/* ==================================================================== */
--/*      Extract vertices for a point.                                   */
--/* ==================================================================== */
--    else if( psShape->nSHPType == SHPT_POINT
--             || psShape->nSHPType == SHPT_POINTM
--             || psShape->nSHPType == SHPT_POINTZ )
--    {
--        int   nOffset;
--
--        psShape->nVertices = 1;
--        if( psShape->bFastModeReadObject )
--        {
--            psShape->padfX = &(psShape->dfXMin);
--            psShape->padfY = &(psShape->dfYMin);
--            psShape->padfZ = &(psShape->dfZMin);
--            psShape->padfM = &(psShape->dfMMin);
--            psShape->padfZ[0] = 0.0;
--            psShape->padfM[0] = 0.0;
--        }
--        else
--        {
--            psShape->padfX = STATIC_CAST(double *, calloc(1,sizeof(double)));
--            psShape->padfY = STATIC_CAST(double *, calloc(1,sizeof(double)));
--            psShape->padfZ = STATIC_CAST(double *, calloc(1,sizeof(double)));
--            psShape->padfM = STATIC_CAST(double *, calloc(1,sizeof(double)));
--        }
--
--        if (20 + 8 + (( psShape->nSHPType == SHPT_POINTZ ) ? 8 : 0)> nEntitySize)
--        {
--            snprintf(szErrorMsg, sizeof(szErrorMsg),
--                     "Corrupted .shp file : shape %d : nEntitySize = %d",
--                     hEntity, nEntitySize);
--            szErrorMsg[sizeof(szErrorMsg)-1] = '\0';
--            psSHP->sHooks.Error( szErrorMsg );
--            SHPDestroyObject(psShape);
--            return SHPLIB_NULLPTR;
--        }
--        memcpy( psShape->padfX, psSHP->pabyRec + 12, 8 );
--        memcpy( psShape->padfY, psSHP->pabyRec + 20, 8 );
--
--        if( bBigEndian ) SwapWord( 8, psShape->padfX );
--        if( bBigEndian ) SwapWord( 8, psShape->padfY );
--
--        nOffset = 20 + 8;
--
--/* -------------------------------------------------------------------- */
--/*      If we have a Z coordinate, collect that now.                    */
--/* -------------------------------------------------------------------- */
--        if( psShape->nSHPType == SHPT_POINTZ )
--        {
--            memcpy( psShape->padfZ, psSHP->pabyRec + nOffset, 8 );
--
--            if( bBigEndian ) SwapWord( 8, psShape->padfZ );
--
--            nOffset += 8;
--        }
--
--/* -------------------------------------------------------------------- */
--/*      If we have a M measure value, then read it now.  We assume      */
--/*      that the measure can be present for any shape if the size is    */
--/*      big enough, but really it will only occur for the Z shapes      */
--/*      (options), and the M shapes.                                    */
--/* -------------------------------------------------------------------- */
--        if( nEntitySize >= nOffset + 8 )
--        {
--            memcpy( psShape->padfM, psSHP->pabyRec + nOffset, 8 );
--
--            if( bBigEndian ) SwapWord( 8, psShape->padfM );
--            psShape->bMeasureIsUsed = TRUE;
--        }
--
--/* -------------------------------------------------------------------- */
--/*      Since no extents are supplied in the record, we will apply      */
--/*      them from the single vertex.                                    */
--/* -------------------------------------------------------------------- */
--        psShape->dfXMin = psShape->dfXMax = psShape->padfX[0];
--        psShape->dfYMin = psShape->dfYMax = psShape->padfY[0];
--        psShape->dfZMin = psShape->dfZMax = psShape->padfZ[0];
--        psShape->dfMMin = psShape->dfMMax = psShape->padfM[0];
--    }
--
--    return( psShape );
--}
--
--/************************************************************************/
--/*                            SHPTypeName()                             */
--/************************************************************************/
--
--const char SHPAPI_CALL1(*)
--SHPTypeName( int nSHPType )
--
--{
--    switch( nSHPType )
--    {
--      case SHPT_NULL:
--        return "NullShape";
--
--      case SHPT_POINT:
--        return "Point";
--
--      case SHPT_ARC:
--        return "Arc";
--
--      case SHPT_POLYGON:
--        return "Polygon";
--
--      case SHPT_MULTIPOINT:
--        return "MultiPoint";
--
--      case SHPT_POINTZ:
--        return "PointZ";
--
--      case SHPT_ARCZ:
--        return "ArcZ";
--
--      case SHPT_POLYGONZ:
--        return "PolygonZ";
--
--      case SHPT_MULTIPOINTZ:
--        return "MultiPointZ";
--
--      case SHPT_POINTM:
--        return "PointM";
--
--      case SHPT_ARCM:
--        return "ArcM";
--
--      case SHPT_POLYGONM:
--        return "PolygonM";
--
--      case SHPT_MULTIPOINTM:
--        return "MultiPointM";
--
--      case SHPT_MULTIPATCH:
--        return "MultiPatch";
--
--      default:
--        return "UnknownShapeType";
--    }
--}
--
--/************************************************************************/
--/*                          SHPPartTypeName()                           */
--/************************************************************************/
--
--const char SHPAPI_CALL1(*)
--SHPPartTypeName( int nPartType )
--
--{
--    switch( nPartType )
--    {
--      case SHPP_TRISTRIP:
--        return "TriangleStrip";
--
--      case SHPP_TRIFAN:
--        return "TriangleFan";
--
--      case SHPP_OUTERRING:
--        return "OuterRing";
--
--      case SHPP_INNERRING:
--        return "InnerRing";
--
--      case SHPP_FIRSTRING:
--        return "FirstRing";
--
--      case SHPP_RING:
--        return "Ring";
--
--      default:
--        return "UnknownPartType";
--    }
--}
--
--/************************************************************************/
--/*                          SHPDestroyObject()                          */
--/************************************************************************/
--
--void SHPAPI_CALL
--SHPDestroyObject( SHPObject * psShape )
--
--{
--    if( psShape == SHPLIB_NULLPTR )
--        return;
--
--    if( psShape->bFastModeReadObject )
--    {
--        psShape->bFastModeReadObject = FALSE;
--        return;
--    }
--
--    if( psShape->padfX != SHPLIB_NULLPTR )
--        free( psShape->padfX );
--    if( psShape->padfY != SHPLIB_NULLPTR )
--        free( psShape->padfY );
--    if( psShape->padfZ != SHPLIB_NULLPTR )
--        free( psShape->padfZ );
--    if( psShape->padfM != SHPLIB_NULLPTR )
--        free( psShape->padfM );
--
--    if( psShape->panPartStart != SHPLIB_NULLPTR )
--        free( psShape->panPartStart );
--    if( psShape->panPartType != SHPLIB_NULLPTR )
--        free( psShape->panPartType );
--
--    free( psShape );
--}
--
--/************************************************************************/
--/*                       SHPGetPartVertexCount()                        */
--/************************************************************************/
--
--static int SHPGetPartVertexCount( const SHPObject * psObject, int iPart )
--{
--    if( iPart == psObject->nParts-1 )
--        return psObject->nVertices - psObject->panPartStart[iPart];
--    else
--        return psObject->panPartStart[iPart+1] - psObject->panPartStart[iPart];
--}
--
--/************************************************************************/
--/*                      SHPRewindIsInnerRing()                          */
--/************************************************************************/
--
--static int SHPRewindIsInnerRing( const SHPObject * psObject,
--                                 int iOpRing )
--{
--/* -------------------------------------------------------------------- */
--/*      Determine if this ring is an inner ring or an outer ring        */
--/*      relative to all the other rings.  For now we assume the         */
--/*      first ring is outer and all others are inner, but eventually    */
--/*      we need to fix this to handle multiple island polygons and      */
--/*      unordered sets of rings.                                        */
--/*                                                                      */
--/* -------------------------------------------------------------------- */
--
--    /* Use point in the middle of segment to avoid testing
--     * common points of rings.
--     */
--    const int iOpRingStart = psObject->panPartStart[iOpRing];
--    double dfTestX = ( psObject->padfX[iOpRingStart] +
--                       psObject->padfX[iOpRingStart + 1] ) / 2;
--    double dfTestY = ( psObject->padfY[iOpRingStart] +
--                       psObject->padfY[iOpRingStart + 1] ) / 2;
--
--    int bInner = FALSE;
--    int iCheckRing;
--    for( iCheckRing = 0; iCheckRing < psObject->nParts; iCheckRing++ )
--    {
--        int nVertStartCheck, nVertCountCheck;
--        int iEdge;
--
--        if( iCheckRing == iOpRing )
--            continue;
--
--        nVertStartCheck = psObject->panPartStart[iCheckRing];
--        nVertCountCheck = SHPGetPartVertexCount(psObject, iCheckRing);
--
--        for( iEdge = 0; iEdge < nVertCountCheck; iEdge++ )
--        {
--            int iNext;
--
--            if( iEdge < nVertCountCheck-1 )
--                iNext = iEdge+1;
--            else
--                iNext = 0;
--
--            /* Rule #1:
--             * Test whether the edge 'straddles' the horizontal ray from
--             * the test point (dfTestY,dfTestY)
--             * The rule #1 also excludes edges colinear with the ray.
--             */
--            if ( ( psObject->padfY[iEdge+nVertStartCheck] < dfTestY
--                    && dfTestY <= psObject->padfY[iNext+nVertStartCheck] )
--                    || ( psObject->padfY[iNext+nVertStartCheck] < dfTestY
--                        && dfTestY <= psObject->padfY[iEdge+nVertStartCheck] ) )
--            {
--                /* Rule #2:
--                 * Test if edge-ray intersection is on the right from the
--                 * test point (dfTestY,dfTestY)
--                 */
--                double const intersect =
--                    ( psObject->padfX[iEdge+nVertStartCheck]
--                        + ( dfTestY - psObject->padfY[iEdge+nVertStartCheck] )
--                        / ( psObject->padfY[iNext+nVertStartCheck] -
--                            psObject->padfY[iEdge+nVertStartCheck] )
--                        * ( psObject->padfX[iNext+nVertStartCheck] -
--                            psObject->padfX[iEdge+nVertStartCheck] ) );
--
--                if (intersect  < dfTestX)
--                {
--                    bInner = !bInner;
--                }
--            }
--        }
--    } /* for iCheckRing */
--    return bInner;
--}
--
--/************************************************************************/
--/*                          SHPRewindObject()                           */
--/*                                                                      */
--/*      Reset the winding of polygon objects to adhere to the           */
--/*      specification.                                                  */
--/************************************************************************/
--
--int SHPAPI_CALL
--SHPRewindObject( CPL_UNUSED SHPHandle hSHP,
--                 SHPObject * psObject )
--{
--    int  iOpRing, bAltered = 0;
--
--/* -------------------------------------------------------------------- */
--/*      Do nothing if this is not a polygon object.                     */
--/* -------------------------------------------------------------------- */
--    if( psObject->nSHPType != SHPT_POLYGON
--        && psObject->nSHPType != SHPT_POLYGONZ
--        && psObject->nSHPType != SHPT_POLYGONM )
--        return 0;
--
--    if( psObject->nVertices == 0 || psObject->nParts == 0 )
--        return 0;
--
--/* -------------------------------------------------------------------- */
--/*      Process each of the rings.                                      */
--/* -------------------------------------------------------------------- */
--    for( iOpRing = 0; iOpRing < psObject->nParts; iOpRing++ )
--    {
--        int      bInner, iVert, nVertCount, nVertStart;
--        double   dfSum;
--
--        nVertStart = psObject->panPartStart[iOpRing];
--        nVertCount = SHPGetPartVertexCount(psObject, iOpRing);
--
--        if (nVertCount < 2)
--            continue;
--
--        bInner = SHPRewindIsInnerRing(psObject, iOpRing);
--
--/* -------------------------------------------------------------------- */
--/*      Determine the current order of this ring so we will know if     */
--/*      it has to be reversed.                                          */
--/* -------------------------------------------------------------------- */
--
--        dfSum = psObject->padfX[nVertStart] *
--                        (psObject->padfY[nVertStart+1] -
--                         psObject->padfY[nVertStart+nVertCount-1]);
--        for( iVert = nVertStart + 1; iVert < nVertStart+nVertCount-1; iVert++ )
--        {
--            dfSum += psObject->padfX[iVert] * (psObject->padfY[iVert+1] -
--                                               psObject->padfY[iVert-1]);
--        }
--
--        dfSum += psObject->padfX[iVert] * (psObject->padfY[nVertStart] -
--                                           psObject->padfY[iVert-1]);
--
--/* -------------------------------------------------------------------- */
--/*      Reverse if necessary.                                           */
--/* -------------------------------------------------------------------- */
--        if( (dfSum < 0.0 && bInner) || (dfSum > 0.0 && !bInner) )
--        {
--            int   i;
--
--            bAltered++;
--            for( i = 0; i < nVertCount/2; i++ )
--            {
--                double dfSaved;
--
--                /* Swap X */
--                dfSaved = psObject->padfX[nVertStart+i];
--                psObject->padfX[nVertStart+i] =
--                    psObject->padfX[nVertStart+nVertCount-i-1];
--                psObject->padfX[nVertStart+nVertCount-i-1] = dfSaved;
--
--                /* Swap Y */
--                dfSaved = psObject->padfY[nVertStart+i];
--                psObject->padfY[nVertStart+i] =
--                    psObject->padfY[nVertStart+nVertCount-i-1];
--                psObject->padfY[nVertStart+nVertCount-i-1] = dfSaved;
--
--                /* Swap Z */
--                if( psObject->padfZ )
--                {
--                    dfSaved = psObject->padfZ[nVertStart+i];
--                    psObject->padfZ[nVertStart+i] =
--                        psObject->padfZ[nVertStart+nVertCount-i-1];
--                    psObject->padfZ[nVertStart+nVertCount-i-1] = dfSaved;
--                }
--
--                /* Swap M */
--                if( psObject->padfM )
--                {
--                    dfSaved = psObject->padfM[nVertStart+i];
--                    psObject->padfM[nVertStart+i] =
--                        psObject->padfM[nVertStart+nVertCount-i-1];
--                    psObject->padfM[nVertStart+nVertCount-i-1] = dfSaved;
--                }
--            }
--        }
--    }
--
--    return bAltered;
--}
diff --cc tools/qtci/LICENSE
index 8dada3edaf50dbc082c9a125058f25def75e625a,8dada3edaf50dbc082c9a125058f25def75e625a..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,201 -1,201 +1,0 @@@
--                                 Apache License
--                           Version 2.0, January 2004
--                        http://www.apache.org/licenses/
--
--   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
--
--   1. Definitions.
--
--      "License" shall mean the terms and conditions for use, reproduction,
--      and distribution as defined by Sections 1 through 9 of this document.
--
--      "Licensor" shall mean the copyright owner or entity authorized by
--      the copyright owner that is granting the License.
--
--      "Legal Entity" shall mean the union of the acting entity and all
--      other entities that control, are controlled by, or are under common
--      control with that entity. For the purposes of this definition,
--      "control" means (i) the power, direct or indirect, to cause the
--      direction or management of such entity, whether by contract or
--      otherwise, or (ii) ownership of fifty percent (50%) or more of the
--      outstanding shares, or (iii) beneficial ownership of such entity.
--
--      "You" (or "Your") shall mean an individual or Legal Entity
--      exercising permissions granted by this License.
--
--      "Source" form shall mean the preferred form for making modifications,
--      including but not limited to software source code, documentation
--      source, and configuration files.
--
--      "Object" form shall mean any form resulting from mechanical
--      transformation or translation of a Source form, including but
--      not limited to compiled object code, generated documentation,
--      and conversions to other media types.
--
--      "Work" shall mean the work of authorship, whether in Source or
--      Object form, made available under the License, as indicated by a
--      copyright notice that is included in or attached to the work
--      (an example is provided in the Appendix below).
--
--      "Derivative Works" shall mean any work, whether in Source or Object
--      form, that is based on (or derived from) the Work and for which the
--      editorial revisions, annotations, elaborations, or other modifications
--      represent, as a whole, an original work of authorship. For the purposes
--      of this License, Derivative Works shall not include works that remain
--      separable from, or merely link (or bind by name) to the interfaces of,
--      the Work and Derivative Works thereof.
--
--      "Contribution" shall mean any work of authorship, including
--      the original version of the Work and any modifications or additions
--      to that Work or Derivative Works thereof, that is intentionally
--      submitted to Licensor for inclusion in the Work by the copyright owner
--      or by an individual or Legal Entity authorized to submit on behalf of
--      the copyright owner. For the purposes of this definition, "submitted"
--      means any form of electronic, verbal, or written communication sent
--      to the Licensor or its representatives, including but not limited to
--      communication on electronic mailing lists, source code control systems,
--      and issue tracking systems that are managed by, or on behalf of, the
--      Licensor for the purpose of discussing and improving the Work, but
--      excluding communication that is conspicuously marked or otherwise
--      designated in writing by the copyright owner as "Not a Contribution."
--
--      "Contributor" shall mean Licensor and any individual or Legal Entity
--      on behalf of whom a Contribution has been received by Licensor and
--      subsequently incorporated within the Work.
--
--   2. Grant of Copyright License. Subject to the terms and conditions of
--      this License, each Contributor hereby grants to You a perpetual,
--      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
--      copyright license to reproduce, prepare Derivative Works of,
--      publicly display, publicly perform, sublicense, and distribute the
--      Work and such Derivative Works in Source or Object form.
--
--   3. Grant of Patent License. Subject to the terms and conditions of
--      this License, each Contributor hereby grants to You a perpetual,
--      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
--      (except as stated in this section) patent license to make, have made,
--      use, offer to sell, sell, import, and otherwise transfer the Work,
--      where such license applies only to those patent claims licensable
--      by such Contributor that are necessarily infringed by their
--      Contribution(s) alone or by combination of their Contribution(s)
--      with the Work to which such Contribution(s) was submitted. If You
--      institute patent litigation against any entity (including a
--      cross-claim or counterclaim in a lawsuit) alleging that the Work
--      or a Contribution incorporated within the Work constitutes direct
--      or contributory patent infringement, then any patent licenses
--      granted to You under this License for that Work shall terminate
--      as of the date such litigation is filed.
--
--   4. Redistribution. You may reproduce and distribute copies of the
--      Work or Derivative Works thereof in any medium, with or without
--      modifications, and in Source or Object form, provided that You
--      meet the following conditions:
--
--      (a) You must give any other recipients of the Work or
--          Derivative Works a copy of this License; and
--
--      (b) You must cause any modified files to carry prominent notices
--          stating that You changed the files; and
--
--      (c) You must retain, in the Source form of any Derivative Works
--          that You distribute, all copyright, patent, trademark, and
--          attribution notices from the Source form of the Work,
--          excluding those notices that do not pertain to any part of
--          the Derivative Works; and
--
--      (d) If the Work includes a "NOTICE" text file as part of its
--          distribution, then any Derivative Works that You distribute must
--          include a readable copy of the attribution notices contained
--          within such NOTICE file, excluding those notices that do not
--          pertain to any part of the Derivative Works, in at least one
--          of the following places: within a NOTICE text file distributed
--          as part of the Derivative Works; within the Source form or
--          documentation, if provided along with the Derivative Works; or,
--          within a display generated by the Derivative Works, if and
--          wherever such third-party notices normally appear. The contents
--          of the NOTICE file are for informational purposes only and
--          do not modify the License. You may add Your own attribution
--          notices within Derivative Works that You distribute, alongside
--          or as an addendum to the NOTICE text from the Work, provided
--          that such additional attribution notices cannot be construed
--          as modifying the License.
--
--      You may add Your own copyright statement to Your modifications and
--      may provide additional or different license terms and conditions
--      for use, reproduction, or distribution of Your modifications, or
--      for any such Derivative Works as a whole, provided Your use,
--      reproduction, and distribution of the Work otherwise complies with
--      the conditions stated in this License.
--
--   5. Submission of Contributions. Unless You explicitly state otherwise,
--      any Contribution intentionally submitted for inclusion in the Work
--      by You to the Licensor shall be under the terms and conditions of
--      this License, without any additional terms or conditions.
--      Notwithstanding the above, nothing herein shall supersede or modify
--      the terms of any separate license agreement you may have executed
--      with Licensor regarding such Contributions.
--
--   6. Trademarks. This License does not grant permission to use the trade
--      names, trademarks, service marks, or product names of the Licensor,
--      except as required for reasonable and customary use in describing the
--      origin of the Work and reproducing the content of the NOTICE file.
--
--   7. Disclaimer of Warranty. Unless required by applicable law or
--      agreed to in writing, Licensor provides the Work (and each
--      Contributor provides its Contributions) on an "AS IS" BASIS,
--      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
--      implied, including, without limitation, any warranties or conditions
--      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
--      PARTICULAR PURPOSE. You are solely responsible for determining the
--      appropriateness of using or redistributing the Work and assume any
--      risks associated with Your exercise of permissions under this License.
--
--   8. Limitation of Liability. In no event and under no legal theory,
--      whether in tort (including negligence), contract, or otherwise,
--      unless required by applicable law (such as deliberate and grossly
--      negligent acts) or agreed to in writing, shall any Contributor be
--      liable to You for damages, including any direct, indirect, special,
--      incidental, or consequential damages of any character arising as a
--      result of this License or out of the use or inability to use the
--      Work (including but not limited to damages for loss of goodwill,
--      work stoppage, computer failure or malfunction, or any and all
--      other commercial damages or losses), even if such Contributor
--      has been advised of the possibility of such damages.
--
--   9. Accepting Warranty or Additional Liability. While redistributing
--      the Work or Derivative Works thereof, You may choose to offer,
--      and charge a fee for, acceptance of support, warranty, indemnity,
--      or other liability obligations and/or rights consistent with this
--      License. However, in accepting such obligations, You may act only
--      on Your own behalf and on Your sole responsibility, not on behalf
--      of any other Contributor, and only if You agree to indemnify,
--      defend, and hold each Contributor harmless for any liability
--      incurred by, or claims asserted against, such Contributor by reason
--      of your accepting any such warranty or additional liability.
--
--   END OF TERMS AND CONDITIONS
--
--   APPENDIX: How to apply the Apache License to your work.
--
--      To apply the Apache License to your work, attach the following
--      boilerplate notice, with the fields enclosed by brackets "{}"
--      replaced with your own identifying information. (Don't include
--      the brackets!)  The text should be enclosed in the appropriate
--      comment syntax for the file format. We also recommend that a
--      file or class name and description of purpose be included on the
--      same "printed page" as the copyright notice for easier
--      identification within third-party archives.
--
--   Copyright {yyyy} {name of copyright owner}
--
--   Licensed under the Apache License, Version 2.0 (the "License");
--   you may not use this file except in compliance with the License.
--   You may obtain a copy of the License at
--
--       http://www.apache.org/licenses/LICENSE-2.0
--
--   Unless required by applicable law or agreed to in writing, software
--   distributed under the License is distributed on an "AS IS" BASIS,
--   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--   See the License for the specific language governing permissions and
--   limitations under the License.
diff --cc tools/qtci/README.gpsbabel
index 614c5bd8d8a9dfbc790f5ee80a632b650d9ab106,614c5bd8d8a9dfbc790f5ee80a632b650d9ab106..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1 -1,1 +1,0 @@@
--The files extract-qt-installer, install-qt, qt-install.qs, LICENSE, and README.md are from https://github.com/benlau/qtci
diff --cc tools/qtci/README.md
index d1a7df6441a7d6b3d8ee8105fdead614c074c0fc,d1a7df6441a7d6b3d8ee8105fdead614c074c0fc..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,164 -1,164 +1,0 @@@
--# QT-CI
--This project collects a set of script for building Qt application for Android/iOS in command line environment.
--
--[![Build Status](https://travis-ci.org/benlau/qtci.svg?branch=master)](https://travis-ci.org/benlau/qtci)
--
--Check [.travis.yml](https://github.com/benlau/qtci/blob/master/.travis.yml) to see how it works.
--It will demonstrate how to build an apk file using QT-CI scripts.
--
--Installation
--============
--
--Since this project is a collection of scripts, and the script in the bin folder does not have any dependence on each other.
--It is not necessary to clone/download the whole repository into your build environment.
--You may simply copy the script you need from this repository.
--
--**recipes/install-qt**
--
--To automatically install Qt, you can just download 2 scripts and grant them permission for execution.
--
--"recipes/install-qt"
--"bin/extract-qt-installer"
--
--Then just run script "recipes/install-qt" with the desired version of Qt
--Example:
--
--    bash install-qt 5.9.4
--
--Enviroument variables
--=====================
--
--QT_CI_PACKAGES - packages to install. You can check available packages if set VERBOSE to 1.
--
--Example:
--
--    export VERBOSE=1
--    export QT_CI_PACKAGES=qt,qt.594,qt.594.gcc_64,qt.594.doc.qtvirtualkeyboard
--
--Setup
--=====
--
--    git clone https://github.com/benlau/qtci.git
--
--    source qtci/path.env #Add qtci/bin and qtci/recipes to $PATH
--
--
--Script
--======
--
--**(1) bin/extract-qt-installer**
----------------------------------
--
--Usage
--
--```
--    extract-qt-installer [--disable-progress-report] qt-installer output_path
--    extract-qt-installer --list-packages qt-installer
--```
--
--Extract Qt from the installer to the target path (for Qt 5.5 or above). If --list-packages is given, it will show the available packages from the installer and terminate immediately. 
--
--Example:
--
--    extract-qt-installer qt-opensource-linux-x64-android-5.5.1.run ~/Qt
--
--**Remarks: The installation path must be absolute path**
--
--Environment Variables
--
--    VERBOSE [Optional] Set to "true" will enable VERBOSE output
--    QT_CI_PACKAGES [Optional] Select the components to be installed instead of using default (eg. QT_CI_PACKAGES="qt.59.gcc_64")
--    QT_CI_LOGIN [Optional] The login name 
--    QT_CI_PASSWORD [Optional] The password of login
--
--The arguments and environment required could be different due to the installer changes. Check the recipes folder or the wiki of known issues to find out the correct setting.
--
--**(2) bin/extract-ifw**
----------------------------------
--
--Extract installer of "Qt installer framework" to the target path
--
--Example:
--
--    extract-ifw qt-installer-framework-opensource-1.5.0-x64.run ~/QtIfw
--
--**(3) bin/install-android-sdk**
----------------------------------
--
--Download and install Android SDK
--
--Example:
--
--    install-android-sdk platform-tool,build-tools-20.0.0,android-19
--
--**(4) bin/build-android-gradle-project**
----------------------------------
--
--Build a Qt Android project and sign the APK
--
--Usage:
--
--    build-android-gradle-project project.pro
--
--Required Environment Variables
--
--    QT_HOME [Required] The home directory of installed Qt. (e.g., ~/Qt/5.7)
--    KEYSTORE [Optional] The location of keystore. If it is set, it will be used to sign the created apk
--    KEYALIAS [Optional] The alias of the keystore
--    KEYPASS  [Optional] The password of keystore.
--        ANDROID_TARGET_SDK_VERSION [Optional] Target Android SDK version. The default value is "19"
--
--(5) bin/increase-android-version-code
----------------------------------
--
--Usage
--
--    increase-android-version-code AndroidManifest.xml
--
--Given an AndroidManifest.xml file, it will increase the value of the versionCode field by one.
--
--(6) bin/run-unittests
------------------------
--
--Usage
--
--    run-unittests project.pro
--
--Build and run a unit test project in the current folder. If qpm.json were found, it would call `qpm install` first.
--
--Recipes
--=======
--
--
--In the folder "recipes", it contains a set of script that could download and install specific Qt toolchains for a different environment. (Include Android)
--
--Please feel free to modify and submit a new recipe.
--
--Example
--
--    apt-get install openjdk-8-jdk p7zip
--
--    source path.env #Add $PWD/bin and $PWD/recipes to $PATH
--
--    #Change to the installation path
--
--    qt-5.5.1-android-19 # Install Qt 5.5.1 and Android SDK
--    
--    source qt-5.5.1-android-19.env # Add installed Qt path to $PATH
--
--
--Reference
--=========
--
-- 1. [Continuous distribution for Qt applications on desktop and mobile](http://www.slidedeck.io/lasconic/qtci-qtcon2016)
-- 1. [Andrew's Articles - Continuous deployment for Qt applications](http://andrewdolby.com/articles/2016/continuous-deployment-for-qt-applications/)
--
--Related Projects
--=================
--
-- 1. [benlau/quickpromise](https://github.com/benlau/quickpromise) - Promise library for QML
-- 2. [benlau/quickcross](https://github.com/benlau/quickcross) - QML Cross Platform Utility Library
-- 3. [benlau/qsyncable](https://github.com/benlau/qsyncable) - Synchronize data between models
-- 4. [benlau/testable](https://github.com/benlau/testable) - QML Unit Test Utilities
-- 5. [benlau/quickflux](https://github.com/benlau/quickflux) - Message Dispatcher / Queue for Qt/QML
-- 6. [benlau/biginteger](https://github.com/benlau/biginteger) - QML BigInteger library
diff --cc tools/qtci/extract-qt-installer
index 073302bdcea1a9c277db335a3cdb31ca6fa2dace,073302bdcea1a9c277db335a3cdb31ca6fa2dace..0000000000000000000000000000000000000000
deleted file mode 100755,100755
+++ /dev/null
@@@ -1,109 -1,109 +1,0 @@@
--#!/bin/bash
--# QT-CI Project
--# License: Apache-2.0
--# https://github.com/benlau/qtci
--
--function usage() {
--    echo "Usage:"
--    echo "extract-qt-installer qt-installer output_path"
--    echo "extract-qt-installer --list-packages qt-installer"
--    exit -1
--}
--
--LIST_PACKAGES=0
--
--getopt --test > /dev/null 2>&1
--GETOPT_RET_CODE=$?
--
--set -e #quit on error
--
--if [ "$GETOPT_RET_CODE" != "4" ]
--then
--    echo "Warning: gnu-getopt is not installed. Long parameter like '--list-package' will not be working. Please install gnu-getopt by 'brew install gnu-getopt'"   
--else
--
--      OPTS=`getopt -o l --long list-packages --long disable-progress-report -n "extract-qt-installer" -- "$@"`
--
--    eval set -- "$OPTS"
--
--    while true
--    do
--      case "$1" in
--        --list-packages)
--          LIST_PACKAGES=1
--          shift;;
--          --disable-progress-report)
--            DISABLE_PROGRESS_REPORT=1
--            shift;;
--        --) shift;break;;
--        *) shift;;
--      esac
--    done
--fi
--
--
--export PATH=$PATH:$PWD
--export WORKDIR=$PWD
--INSTALLER=$1
--OUTPUT=$2
--SCRIPT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/qt-install.qs
--PACKAGES=$QT_CI_PACKAGES
--
--if [ $LIST_PACKAGES -gt 0 ]
--then 
--
--      if [ $# -lt 1 ]
--      then
--              usage
--      fi
--      
--      OUTPUT="/tmp/Qt"
--
--else
--
--      if [ $# -lt 2 ]
--      then
--              usage
--      fi
--
--      if [[ ! "${OUTPUT:0:1}" = "/" ]] 
--      then 
--              echo output path must be an absolute path
--              exit -1
--      fi
--    
--fi
--
--
--chmod u+x $1
--if [ -n "$QT_CI_DEBUG" ] 
--then
--      $INSTALLER -v --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT" | grep "\(QTCI\|operation\)"
--      exit 0
--fi
--
--unset DISPLAY
--
--# platform minimal doesn't work on macos 10.14, 10.15.  It did work on 10.13.
--# https://bugreports.qt.io/browse/QTIFW-1471
--PLATFORM="--platform minimal"
--if [ "$(uname)" = "Darwin" ]; then
--  vn=$(sw_vers -productVersion | cut -d. -f2,2)
--  if [ $vn -ge 14 ]; then
--     unset PLATFORM
--  fi
--fi
--
--if [ -n "$DISABLE_PROGRESS_REPORT" ]
--then
--      $INSTALLER $PLATFORM --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT" 
--else
--      if [ -n "$VERBOSE" ]
--      then
--              $INSTALLER --verbose $PLATFORM --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT"
--      else
--              $INSTALLER --verbose $PLATFORM --script $SCRIPT QTCI_LIST_PACKAGES="$LIST_PACKAGES" QTCI_PACKAGES="$PACKAGES" QTCI_OUTPUT="$OUTPUT" | grep "\(QTCI\|operation\)"
--      fi
--fi
--
--
diff --cc tools/qtci/find_qt_installer
index d1b5486fdabe734f64f671e0635ac37a409b1fb0,d1b5486fdabe734f64f671e0635ac37a409b1fb0..0000000000000000000000000000000000000000
deleted file mode 100755,100755
+++ /dev/null
@@@ -1,24 -1,24 +1,0 @@@
--#!/bin/bash -e
--# Reference:
--#   https://github.com/musescore/MuseScore/blob/master/build/travis/job_macos/install.sh
--
--QT_VERSION=${1:-5.12.0}
--
--QT_MAJOR_VERSION=$(echo ${QT_VERSION} | cut -d "." -f 1)
--QT_MINOR_VERSION=$(echo ${QT_VERSION} | cut -d "." -f 2)
--if [ "$(uname)" = "Darwin" ]; then
--  if { [ "${QT_MAJOR_VERSION}" -eq 5 ] && [ "${QT_MINOR_VERSION}" -ge 9 ]; } || [ "${QT_MAJOR_VERSION}" -ge 6 ]; then
--    # this was good from 5.9.0 through at least 5.12.0
--    DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-mac-x64-${QT_VERSION}.dmg
--  else
--    # this was good from 5.2.1 through 5.8.0
--    DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-mac-x64-clang-${QT_VERSION}.dmg
--  fi
--elif [ "$(uname)" = "Linux" ]; then
--  # this was good from 5.2.1 through at least 5.12.0
--  DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-linux-x64-${QT_VERSION}.run
--else
--  echo "Unsupported system." >&2
--  exit 1
--fi
--echo $DOWNLOAD_URL
diff --cc tools/qtci/install-qt
index 1b1f4f3283de581e2495c62282e1f13e72d40cfd,1b1f4f3283de581e2495c62282e1f13e72d40cfd..0000000000000000000000000000000000000000
deleted file mode 100755,100755
+++ /dev/null
@@@ -1,62 -1,62 +1,0 @@@
--#!/bin/bash -e
--# Reference:
--#   https://github.com/musescore/MuseScore/blob/master/build/travis/job_macos/install.sh
--
--QT_VERSION=${1:-5.12.0}
--QT_TARGET_CATALOG=${2:-$PWD}
--QT_CI_DOWNLOADER=${QT_CI_DOWNLOADER:-"wget -c -N"}
--
--QT_MAJOR_VERSION=$(echo ${QT_VERSION} | cut -d "." -f 1)
--QT_MINOR_VERSION=$(echo ${QT_VERSION} | cut -d "." -f 2)
--if [ "$(uname)" = "Darwin" ]; then
--  if { [ "${QT_MAJOR_VERSION}" -eq 5 ] && [ "${QT_MINOR_VERSION}" -ge 9 ]; } || [ "${QT_MAJOR_VERSION}" -ge 6 ]; then
--    # this was good from 5.9.0 through at least 5.12.0
--    DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-mac-x64-${QT_VERSION}.dmg
--  else
--    # this was good from 5.2.1 through 5.8.0
--    DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-mac-x64-clang-${QT_VERSION}.dmg
--  fi
--  COMPILER=clang_64
--elif [ "$(uname)" = "Linux" ]; then
--  # this was good from 5.2.1 through at least 5.12.0
--  DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-linux-x64-${QT_VERSION}.run
--  COMPILER=gcc_64
--else
--  echo "Unsupported system." >&2
--  exit 1
--fi
--INSTALLER=$(basename $DOWNLOAD_URL)
--ENVFILE=${QT_TARGET_CATALOG}/qt-${QT_VERSION}.env
--
--echo Downloading Qt
--${QT_CI_DOWNLOADER} ${DOWNLOAD_URL} || exit 1
--
--echo Installing Qt
--if [ "$(uname)" = "Darwin" ]; then
--  INSTALLER_NAME=${INSTALLER%.*}
--  APPFILE=/Volumes/${INSTALLER_NAME}/${INSTALLER_NAME}.app/Contents/MacOS/${INSTALLER_NAME}
--  hdiutil attach ${PWD}/${INSTALLER}
--  sandbox-exec -n no-network extract-qt-installer $APPFILE ${QT_TARGET_CATALOG}/Qt
--  # workaround apparent exit of extract-qt-installer before finished,
--  # which results in hdiutil "hdiutil: couldn't unmount "disk1" - Resource busy"
--  # and the install resources not being available.
--  #hdiutil detach /Volumes/${INSTALLER_NAME}
--  count=0
--  until hdiutil detach /Volumes/${INSTALLER_NAME} || [ $count -ge 12 ]
--  do
--    echo "Wait and attempt to detach again"
--    count=`expr $count + 1`
--    sleep 5
--  done
--elif [ "$(uname)" = "Linux" ]; then
--  unshare -r -n extract-qt-installer ${PWD}/${INSTALLER} ${QT_TARGET_CATALOG}/Qt
--fi
--
--echo Create ${ENVFILE}
--if [ -d "${QT_TARGET_CATALOG}/Qt/${QT_VERSION}/${COMPILER}/bin" ]; then
--  echo "export PATH=${QT_TARGET_CATALOG}/Qt/${QT_VERSION}/${COMPILER}/bin:$PATH" > ${ENVFILE}
--elif [ -d "${QT_TARGET_CATALOG}/Qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${COMPILER}/bin" ]; then
--  # some packages use an abbreviated version x.y in the path instead of x.y.z
--  echo "export PATH=${QT_TARGET_CATALOG}/Qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${COMPILER}/bin:$PATH" > ${ENVFILE}
--fi
--
diff --cc tools/qtci/install-qt-online
index 63d686d73dfd39c8640f921997371dee5fe3de59,63d686d73dfd39c8640f921997371dee5fe3de59..0000000000000000000000000000000000000000
deleted file mode 100755,100755
+++ /dev/null
@@@ -1,62 -1,62 +1,0 @@@
--#!/bin/bash -e
--# Install Qt by online installer
--
--function usage() {
--    echo "Usage:"
--    echo "install-qt-online \"packages\" [output_path [qt_installer_version]]"
--    echo "Examples:"
--    echo "install-qt-online \"qt.qt5.5121.gcc_64\""
--    echo "install-qt-online \"qt.qt5.5121.gcc_64\" /opt/Qt"
--    echo "install-qt-online \"qt.qt5.5121.gcc_64\" /opt/Qt latest"
--    echo "install-qt-online \"qt.qt5.5121.gcc_64\" /opt/Qt 3.1.1"
--    exit -1
--}
--
--if [ $# -lt 1 ]
--then
--      usage
--fi
--
--export QT_CI_PACKAGES=${1}
--QT_TARGET_CATALOG=${2:-$PWD}
--INSTALLER_VERSION=${3:-latest} # lastest or a version triplet, e.g. 3.1.1
--QT_CI_DOWNLOADER=${QT_CI_DOWNLOADER:-"wget -c -N"}
--
--if [ "$(uname)" = "Darwin" ]; then
--  if [ "${INSTALLER_VERSION}" = "latest" ]; then
--    DOWNLOAD_URL=https://download.qt.io/official_releases/online_installers/qt-unified-mac-x64-online.dmg
--  else
--    DOWNLOAD_URL=https://download.qt.io/archive/online_installers/$(echo ${INSTALLER_VERSION} | cut -d . -f1-2)/qt-unified-mac-x64-${INSTALLER_VERSION}-online.dmg
--  fi
--  COMPILER=clang_64
--elif [ "$(uname)" = "Linux" ]; then
--  if [ "${INSTALLER_VERSION}" = "latest" ]; then
--    DOWNLOAD_URL=https://download.qt.io/official_releases/online_installers/qt-unified-linux-x64-online.run
--  else
--    DOWNLOAD_URL=https://download.qt.io/archive/online_installers/$(echo ${INSTALLER_VERSION} | cut -d . -f1-2)/qt-unified-linux-x64-${INSTALLER_VERSION}-online.run
--  fi
--  COMPILER=gcc_64
--else
--  echo "Unsupported system." >&2
--  exit 1
--fi
--
--INSTALLER=$(basename $DOWNLOAD_URL)
--
--echo Downloading Qt
--${QT_CI_DOWNLOADER} ${DOWNLOAD_URL} || exit 1
--
--echo Installing Qt
--
--if [ "$(uname)" = "Darwin" ]; then
--  hdiutil attach ${PWD}/${INSTALLER} -plist > minfo.plist
--  MOUNTPOINT=$(/usr/libexec/PlistBuddy -c "Print :system-entities:0:mount-point" minfo.plist || \
--               /usr/libexec/PlistBuddy -c "Print :system-entities:1:mount-point" minfo.plist || \
--               /usr/libexec/PlistBuddy -c "Print :system-entities:2:mount-point" minfo.plist)
--  INSTALLER_NAME=$(basename "${MOUNTPOINT}")
--  APPFILE="${MOUNTPOINT}"/${INSTALLER_NAME}.app/Contents/MacOS/${INSTALLER_NAME}
--  extract-qt-installer "$APPFILE" "${QT_TARGET_CATALOG}/Qt"
--  hdiutil detach "${MOUNTPOINT}"
--elif [ "$(uname)" = "Linux" ]; then
--  extract-qt-installer ${PWD}/${INSTALLER} "${QT_TARGET_CATALOG}/Qt"
--fi
diff --cc tools/qtci/qt-install.qs
index d711157d1ce07d2cec73a0322f72236808a705d4,d711157d1ce07d2cec73a0322f72236808a705d4..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,256 -1,256 +1,0 @@@
--// QT-CI Project
--// License: Apache-2.0
--// https://github.com/benlau/qtci
--
--function log() {
--    var msg = ["QTCI: "].concat([].slice.call(arguments));
--    console.log(msg.join(" "));
--}
--
--function printObject(object) {
--    var lines = [];
--    for (var i in object) {
--        lines.push([i, object[i]].join(" "));
--    }
--    log(lines.join(","));
--}
--
--var status = {
--    widget: null,
--    finishedPageVisible: false,
--    installationFinished: false
--}
--
--function tryFinish() {
--    if (status.finishedPageVisible && status.installationFinished) {
--        if (status.widget.LaunchQtCreatorCheckBoxForm) {
--            // Disable this checkbox for minimal platform
--            status.widget.LaunchQtCreatorCheckBoxForm.launchQtCreatorCheckBox.setChecked(false);
--        }
--        if (status.widget.RunItCheckBox) {
--            // LaunchQtCreatorCheckBoxForm may not work for newer versions.
--            status.widget.RunItCheckBox.setChecked(false);
--        }
--        log("Press Finish Button");
--        gui.clickButton(buttons.FinishButton);
--    }
--}
--
--function Controller() {
--    installer.installationFinished.connect(function() {
--        status.installationFinished = true;
--        gui.clickButton(buttons.NextButton);
--        tryFinish();
--    });
--    installer.setMessageBoxAutomaticAnswer("OverwriteTargetDirectory", QMessageBox.Yes);
--    installer.setMessageBoxAutomaticAnswer("installationErrorWithRetry", QMessageBox.Ignore);
--    installer.setMessageBoxAutomaticAnswer("XcodeError", QMessageBox.Ok);
--
--    // Allow to cancel installation for arguments --list-packages
--    installer.setMessageBoxAutomaticAnswer("cancelInstallation", QMessageBox.Yes);
--}
--
--Controller.prototype.WelcomePageCallback = function() {
--    log("Welcome Page");
--
--    gui.clickButton(buttons.NextButton);
--
--    var widget = gui.currentPageWidget();
--
--    /* 
--         Online installer 3.0.6 
--         - It must disconnect the completeChanged callback after used, otherwise it will click the 'next' button on another pages
--       */
--    var callback = function() {
--        gui.clickButton(buttons.NextButton);
--        widget.completeChanged.disconnect(callback);
--    }
--
--    widget.completeChanged.connect(callback);
--}
--
--Controller.prototype.CredentialsPageCallback = function() {
--
--    var login = installer.environmentVariable("QT_CI_LOGIN");
--    var password = installer.environmentVariable("QT_CI_PASSWORD");
--
--    if (login === "" || password === "") {
--        gui.clickButton(buttons.CommitButton);
--    }
--
--    var widget = gui.currentPageWidget();
--
--    widget.loginWidget.EmailLineEdit.setText(login);
--
--    widget.loginWidget.PasswordLineEdit.setText(password);
--
--    gui.clickButton(buttons.CommitButton);
--}
--
--Controller.prototype.ComponentSelectionPageCallback = function() {
--    log("ComponentSelectionPageCallback");
--
--    function list_packages() {
--        var components = installer.components();
--        log("Available components: " + components.length);
--        var packages = ["Packages: "];
--
--        for (var i = 0; i < components.length; i++) {
--            packages.push(components[i].name);
--        }
--        log(packages.join(" "));
--    }
--
--    var widget = gui.currentPageWidget();
--
--    var archiveCheckBox = gui.findChild(widget, "Archive");
--    var latestCheckBox = gui.findChild(widget, "Latest releases");
--    var fetchButton = gui.findChild(widget, "FetchCategoryButton");
--
--    if (archiveCheckBox != null) {
--      // check archive
--      archiveCheckBox.click();
--    }
--    if (latestCheckBox != null) {
--      // uncheck latest
--      latestCheckBox.click();
--    }
--    if (fetchButton != null) {
--      fetchButton.click()
--    }
--
--    if (installer.value("QTCI_LIST_PACKAGES", "0") != "0") {
--        list_packages();
--        gui.clickButton(buttons.CancelButton);
--        return;
--    }
--
--    log("Select components");
--
--    function trim(str) {
--        return str.replace(/^ +/, "").replace(/ *$/, "");
--    }
--
--    var packages = trim(installer.value("QTCI_PACKAGES")).split(",");
--    if (packages.length > 0 && packages[0] !== "") {
--        widget.deselectAll();
--        var components = installer.components();
--        var allfound = true;
--        for (var i in packages) {
--            var pkg = trim(packages[i]);
--            var found = false;
--            for (var j in components) {
--                if (components[j].name === pkg) {
--                    found = true;
--                    break;
--                }
--            }
--            if (!found) {
--                allfound = false;
--                log("ERROR: Package " + pkg + " not found.");
--            } else {
--                log("Select " + pkg);
--                widget.selectComponent(pkg);
--            }
--        }
--        if (!allfound) {
--            list_packages();
--            // TODO: figure out how to set non-zero exit status.
--            gui.clickButton(buttons.CancelButton);
--            return;
--        }
--    } else {
--        log("Use default component list");
--    }
--
--    gui.clickButton(buttons.NextButton);
--}
--
--Controller.prototype.IntroductionPageCallback = function() {
--    log("Introduction Page");
--    log("Retrieving meta information from remote repository");
--
--    /* 
--         Online installer 3.0.6 
--         - Don't click buttons.NextButton directly. It will skip the componenet selection.
--    */
--
--    if (installer.isOfflineOnly()) {
--        gui.clickButton(buttons.NextButton);
--    }
--}
--
--Controller.prototype.TargetDirectoryPageCallback = function() {
--    var output = installer.value("QTCI_OUTPUT");
--    log("Set target installation page: " + output);
--    var widget = gui.currentPageWidget();
--
--    if (widget != null) {
--        widget.TargetDirectoryLineEdit.setText(output);
--    }
--
--    gui.clickButton(buttons.NextButton);
--}
--
--Controller.prototype.LicenseAgreementPageCallback = function() {
--    log("Accept license agreement");
--    var widget = gui.currentPageWidget();
--
--    if (widget != null) {
--        widget.AcceptLicenseRadioButton.setChecked(true);
--    }
--
--    gui.clickButton(buttons.NextButton);
--}
--
--Controller.prototype.ReadyForInstallationPageCallback = function() {
--    log("Ready to install");
--
--    // Bug? If commit button pressed too quickly finished callback might not show the checkbox to disable running qt creator
--    // Behaviour started around 5.10. You don't actually have to press this button at all with those versions, even though gui.isButtonEnabled() returns true.
--    gui.clickButton(buttons.CommitButton, 200);
--}
--
--Controller.prototype.PerformInstallationPageCallback = function() {
--    log("PerformInstallationPageCallback");
--    gui.clickButton(buttons.CommitButton);
--}
--
--Controller.prototype.FinishedPageCallback = function() {
--    log("FinishedPageCallback");
--
--    var widget = gui.currentPageWidget();
--
--    // Bug? Qt 5.9.5 and Qt 5.9.6 installer show finished page before the installation completed
--    // Don't press "finishButton" immediately
--    status.finishedPageVisible = true;
--    status.widget = widget;
--    tryFinish();
--}
--
--// Telemetry disabled 
--Controller.prototype.DynamicTelemetryPluginFormCallback = function()
--{
--    log("TelemetryPluginFormCallback");
--    var page = gui.pageWidgetByObjectName("DynamicTelemetryPluginForm");
--    page.statisticGroupBox.disableStatisticRadioButton.setChecked(true);
--    gui.clickButton(buttons.NextButton);
--}
--
--// On windows installs there is a page about the start menu.
--Controller.prototype.StartMenuDirectoryPageCallback = function() {
--    log("StartMenuDirectoryPageCallback");
--    gui.clickButton(buttons.NextButton);
--}
--
--// qt online installer 3.2.1: open source users must now accept the open
--// source obligations.
--// https://www.qt.io/blog/qt-online-installer-3.2.1-released
--Controller.prototype.ObligationsPageCallback = function()
--{
--    log("ObligationsPageCallback");
--    var page = gui.pageWidgetByObjectName("ObligationsPage");
--    page.obligationsAgreement.setChecked(true);
--    page.completeChanged();
--    gui.clickButton(buttons.NextButton);
--}
diff --cc tools/uploadtool/LICENSE
index 03cdbe71e9af0d83ee80738fa98c390df1640f15,03cdbe71e9af0d83ee80738fa98c390df1640f15..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,21 -1,21 +1,0 @@@
--MIT License
--
--Copyright (c) 2016 Simon Peter
--
--Permission is hereby granted, free of charge, to any person obtaining a copy
--of this software and associated documentation files (the "Software"), to deal
--in the Software without restriction, including without limitation the rights
--to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
--copies of the Software, and to permit persons to whom the Software is
--furnished to do so, subject to the following conditions:
--
--The above copyright notice and this permission notice shall be included in all
--copies or substantial portions of the Software.
--
--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
--IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
--FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
--AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
--LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
--OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
--SOFTWARE.
diff --cc tools/uploadtool/README.gpsbabel
index 55f70142e00f3adb9ba550e28d48969f1ebae12a,55f70142e00f3adb9ba550e28d48969f1ebae12a..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1 -1,1 +1,0 @@@
--The files README.md, LICENSE, and upload.sh are from https://github.com/probonopd/uploadtool
diff --cc tools/uploadtool/README.md
index 0a755fc8f62c88045d4b95ea8d948dec40cc1e37,0a755fc8f62c88045d4b95ea8d948dec40cc1e37..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,41 -1,41 +1,0 @@@
--# uploadtool [![Build Status](https://travis-ci.org/probonopd/uploadtool.svg?branch=master)](https://travis-ci.org/probonopd/uploadtool)
--
--Super simple uploading of continuous builds (each push) to GitHub Releases. If this is not the easiest way to upload continuous builds to GitHub Releases, then it is a bug.
--
--## Usage
--
--This script is designed to be called from Travis CI after a successful build. By default, this script will _delete_ any pre-existing release tagged with `continuous`, tag the current state with the name `continuous`, create a new release with that name, and upload the specified binaries there. For pull requests, it will upload the binaries to transfer.sh instead and post the resulting download URL to the pull request page on GitHub.
--
-- - On https://github.com/settings/tokens, click on "Generate new token" and generate a token with at least the `public_repo`, `repo:status`, and `repo_deployment` scopes
-- - On Travis CI, go to the settings of your project at `https://travis-ci.org/yourusername/yourrepository/settings`
-- - Under "Environment Variables", add key `GITHUB_TOKEN` and the token you generated above as the value. **Make sure that "Display value in build log" is set to "OFF"!**
-- - In the `.travis.yml` of your GitHub repository, add something like this (assuming the build artifacts to be uploaded are in out/):
--
--```yaml
--after_success:
--  - ls -lh out/* # Assuming you have some files in out/ that you would like to upload
--  - wget -c https://github.com/probonopd/uploadtool/raw/master/upload.sh
--  - bash upload.sh out/*
--
--branches:
--  except:
--    - # Do not build tags that we create when we upload to GitHub Releases
--    - /^(?i:continuous)$/
--```
--
--## Environment variables
--
--`upload.sh` normally only creates one stream of continuous releases for the latest commits that are pushed into (or merged into) the repository.
--
--It's possible to use `upload.sh` in a more complex manner by setting the environment variable `UPLOADTOOL_SUFFIX`. If this variable is set to the name of the current tag, then `upload.sh` will upload a release to the repository (basically reproducing the `deploy:` feature in `.travis.yml`).
--
--If `UPLOADTOOL_SUFFIX` is set to a different text, then this text is used as suffix for the `continuous` tag that is created for continuous releases. This way, a project can customize what releases are being created.
--One possible use case for this is to set up continuous builds for feature or test branches:
--```
--  if [ ! -z $TRAVIS_BRANCH ] && [ "$TRAVIS_BRANCH" != "master" ] ; then
--    export UPLOADTOOL_SUFFIX=$TRAVIS_BRANCH
--  fi
--```
--This will create builds tagged with `continuous` for pushes / merges to `master` and with `continuous-<branch-name>` for pushes / merges to other branches.
--
--The two environment variables `UPLOADTOOL_PR_BODY` and `UPLOADTOOL_BODY` allow the calling script to customize the messages that are posted either for pull requests or merges / pushes. If these variables aren't set, generic default texts are used.
diff --cc tools/uploadtool/upload.sh
index 5c8ec8bba8a9b155c965e14140205ce399beb1b9,3bc9a272cdd3450c8f925be20200927b7320208f..0000000000000000000000000000000000000000
deleted file mode 100755,100644
+++ /dev/null
@@@ -1,209 -1,205 +1,0 @@@
--#!/bin/bash
--
--set +x # Do not leak information
--
--# Exit immediately if one of the files given as arguments is not there
--# because we don't want to delete the existing release if we don't have
--# the new files that should be uploaded 
--for file in "$@"
--do
--    if [ ! -e "$file" ]
--    then echo "$file is missing, giving up." >&2; exit 1
--    fi
--done
--
--if [ $# -eq 0 ]; then
--    echo "No artifacts to use for release, giving up."
--    exit 0
--fi
--
--if command -v sha256sum >/dev/null 2>&1 ; then
--  shatool="sha256sum"
--elif command -v shasum >/dev/null 2>&1 ; then
--  shatool="shasum -a 256" # macOS fallback
--else
--  echo "Neither sha256sum nor shasum is available, cannot check hashes"
--fi
--
--# The calling script (usually .travis.yml) can set a suffix to be used for
--# the tag and release name. This way it is possible to have a release for
--# the output of the CI/CD pipeline (marked as 'continuous') and also test
--# builds for other branches.
--# If this build was triggered by a tag, call the result a Release
--if [ ! -z "$UPLOADTOOL_SUFFIX" ] ; then
--  if [ "$UPLOADTOOL_SUFFIX" = "$TRAVIS_TAG" ] ; then
-     RELEASE_NAME=$TRAVIS_TAG
 -    RELEASE_NAME="$TRAVIS_TAG"
--    RELEASE_TITLE="Release build ($TRAVIS_TAG)"
--    is_prerelease="false"
--  else
--    RELEASE_NAME="continuous-$UPLOADTOOL_SUFFIX"
--    RELEASE_TITLE="Continuous build ($UPLOADTOOL_SUFFIX)"
--    is_prerelease="true"
--  fi
--else
-   RELEASE_NAME="continuous" # Do not use "latest" as it is reserved by GitHub
 -  # Do not use "latest" as it is reserved by GitHub
 -  RELEASE_NAME="continuous"
--  RELEASE_TITLE="Continuous build"
--  is_prerelease="true"
--fi
--
--if [ "$TRAVIS_EVENT_TYPE" == "pull_request" ] ; then
-   echo "Release uploading disabled for pull requests, uploading to transfer.sh instead"
 -  echo "Release uploading disabled for pull requests, uploading to transfersh.com instead"
--  rm -f ./uploaded-to
--  for FILE in "$@" ; do
--    BASENAME="$(basename "${FILE}")"
-     echo "Uploading $BASENAME to upload.sh has been suspended as o 03/16 -- rjl"
-     break
-     curl --upload-file $FILE "https://transfer.sh/$BASENAME" > ./one-upload
 -      curl --upload-file $FILE "https://transfersh.com/$BASENAME" > ./one-upload
--    echo "$(cat ./one-upload)" # this way we get a newline
--    echo -n "$(cat ./one-upload)\\n" >> ./uploaded-to # this way we get a \n but no newline
--  done
--#  review_url="https://api.github.com/repos/${TRAVIS_REPO_SLUG}/pulls/${TRAVIS_PULL_REQUEST}/reviews"
--#  if [ -z $UPLOADTOOL_PR_BODY ] ; then
--#    body="Travis CI has created build artifacts for this PR here:"
--#  else
--#    body="$UPLOADTOOL_PR_BODY"
--#  fi
--#  body="$body\n$(cat ./uploaded-to)\nThe link(s) will expire 14 days from now."
--#  review_comment=$(curl -X POST \
--#    --header "Authorization: token ${GITHUB_TOKEN}" \
--#    --data '{"commit_id": "'"$TRAVIS_COMMIT"'","body": "'"$body"'","event": "COMMENT"}' \
--#    $review_url)
--#  if echo $review_comment | grep -q "Bad credentials" 2>/dev/null ; then
--#    echo '"Bad credentials" response for --data {"commit_id": "'"$TRAVIS_COMMIT"'","body": "'"$body"'","event": "COMMENT"}'
--#  fi
--  $shatool "$@"
--  exit 0
--fi
--
--if [ ! -z "$TRAVIS_REPO_SLUG" ] ; then
--  # We are running on Travis CI
--  echo "Running on Travis CI"
--  echo "TRAVIS_COMMIT: $TRAVIS_COMMIT"
--  REPO_SLUG="$TRAVIS_REPO_SLUG"
--  if [ -z "$GITHUB_TOKEN" ] ; then
--    echo "\$GITHUB_TOKEN missing, please set it in the Travis CI settings of this project"
--    echo "You can get one from https://github.com/settings/tokens"
--    exit 1
--  fi
--else
--  # We are not running on Travis CI
--  echo "Not running on Travis CI"
--  if [ -z "$REPO_SLUG" ] ; then
-     read -r -s -p "Repo Slug (GitHub and Travis CI username/reponame): " REPO_SLUG
 -    read -r -p "Repo Slug (GitHub and Travis CI username/reponame): " REPO_SLUG
--  fi
--  if [ -z "$GITHUB_TOKEN" ] ; then
--    read -r -s -p "Token (https://github.com/settings/tokens): " GITHUB_TOKEN
--  fi
--fi
--
--tag_url="https://api.github.com/repos/$REPO_SLUG/git/refs/tags/$RELEASE_NAME"
--tag_infos=$(curl -XGET --header "Authorization: token ${GITHUB_TOKEN}" "${tag_url}")
--echo "tag_infos: $tag_infos"
--tag_sha=$(echo "$tag_infos" | grep '"sha":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "tag_sha: $tag_sha"
--
--release_url="https://api.github.com/repos/$REPO_SLUG/releases/tags/$RELEASE_NAME"
--echo "Getting the release ID..."
--echo "release_url: $release_url"
--release_infos=$(curl -XGET --header "Authorization: token ${GITHUB_TOKEN}" "${release_url}")
--echo "release_infos: $release_infos"
--release_id=$(echo "$release_infos" | grep "\"id\":" | head -n 1 | tr -s " " | cut -f 3 -d" " | cut -f 1 -d ",")
--echo "release ID: $release_id"
--upload_url=$(echo "$release_infos" | grep '"upload_url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "upload_url: $upload_url"
--release_url=$(echo "$release_infos" | grep '"url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "release_url: $release_url"
--target_commit_sha=$(echo "$release_infos" | grep '"target_commitish":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "target_commit_sha: $target_commit_sha"
--
--if [ "$TRAVIS_COMMIT" != "$target_commit_sha" ] ; then
--
--  echo "TRAVIS_COMMIT != target_commit_sha, hence deleting $RELEASE_NAME..."
--  
--  if [ ! -z "$release_id" ]; then
--    delete_url="https://api.github.com/repos/$REPO_SLUG/releases/$release_id"
--    echo "Delete the release..."
--    echo "delete_url: $delete_url"
--    curl -XDELETE \
--        --header "Authorization: token ${GITHUB_TOKEN}" \
--        "${delete_url}"
--  fi
--
--  # echo "Checking if release with the same name is still there..."
--  # echo "release_url: $release_url"
--  # curl -XGET --header "Authorization: token ${GITHUB_TOKEN}" \
--  #     "$release_url"
--
-   if [ "$is_prerelease" = "true" ] ; then
 -  if [ "$RELEASE_NAME" == "continuous" ] ; then
--    # if this is a continuous build tag, then delete the old tag
--    # in preparation for the new release
--    echo "Delete the tag..."
--    delete_url="https://api.github.com/repos/$REPO_SLUG/git/refs/tags/$RELEASE_NAME"
--    echo "delete_url: $delete_url"
--    curl -XDELETE \
--        --header "Authorization: token ${GITHUB_TOKEN}" \
--        "${delete_url}"
--  fi
--
--  echo "Create release..."
--
--  if [ -z "$TRAVIS_BRANCH" ] ; then
--    TRAVIS_BRANCH="master"
--  fi
--
--  if [ ! -z "$TRAVIS_JOB_ID" ] ; then
--    if [ -z "${UPLOADTOOL_BODY+x}" ] ; then
-       # TODO: The host could be travis-ci.org (legacy open source) or travis-ci.com (subscription or latest open source).
-       BODY="Travis CI build log: https://travis-ci.com/$REPO_SLUG/builds/$TRAVIS_BUILD_ID/"
 -      BODY="Travis CI build log: ${TRAVIS_BUILD_WEB_URL}"
--    else
--      BODY="$UPLOADTOOL_BODY"
--    fi
--  else
--    BODY="$UPLOADTOOL_BODY"
--  fi
--
--  release_infos=$(curl -H "Authorization: token ${GITHUB_TOKEN}" \
--       --data '{"tag_name": "'"$RELEASE_NAME"'","target_commitish": "'"$TRAVIS_COMMIT"'","name": "'"$RELEASE_TITLE"'","body": "'"$BODY"'","draft": false,"prerelease": '$is_prerelease'}' "https://api.github.com/repos/$REPO_SLUG/releases")
--
--  echo "$release_infos"
--
--  unset upload_url
--  upload_url=$(echo "$release_infos" | grep '"upload_url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--  echo "upload_url: $upload_url"
--
--  unset release_url
--  release_url=$(echo "$release_infos" | grep '"url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--  echo "release_url: $release_url"
--
--fi # if [ "$TRAVIS_COMMIT" != "$tag_sha" ]
--
--if [ -z "$release_url" ] ; then
--      echo "Cannot figure out the release URL for $RELEASE_NAME"
--      exit 1
--fi
--
--echo "Upload binaries to the release..."
--
--for FILE in "$@" ; do
--  FULLNAME="${FILE}"
--  BASENAME="$(basename "${FILE}")"
--  curl -H "Authorization: token ${GITHUB_TOKEN}" \
--       -H "Accept: application/vnd.github.manifold-preview" \
--       -H "Content-Type: application/octet-stream" \
--       --data-binary @$FULLNAME \
--       "$upload_url?name=$BASENAME"
--  echo ""
--done
--
--$shatool "$@"
--
--if [ "$TRAVIS_COMMIT" != "$tag_sha" ] ; then
--  echo "Publish the release..."
--
--  release_infos=$(curl -H "Authorization: token ${GITHUB_TOKEN}" \
--       --data '{"draft": false}' "$release_url")
--
--  echo "$release_infos"
--fi # if [ "$TRAVIS_COMMIT" != "$tag_sha" ]
diff --cc tools/uploadtool/upload_appveyor.sh
index 6c10cb114b7c0a96c71ed701f684a14c9df8a3e0,6c10cb114b7c0a96c71ed701f684a14c9df8a3e0..0000000000000000000000000000000000000000
deleted file mode 100755,100755
+++ /dev/null
@@@ -1,216 -1,216 +1,0 @@@
--#!/bin/bash
--
--set +x # Do not leak information
--
--# Exit immediately if one of the files given as arguments is not there
--# because we don't want to delete the existing release if we don't have
--# the new files that should be uploaded 
--for file in "$@"
--do
--    if [ ! -e "$file" ]
--    then echo "$file is missing, giving up." >&2; exit 1
--    fi
--done
--
--if [ $# -eq 0 ]; then
--    echo "No artifacts to use for release, giving up."
--    exit 0
--fi
--
--if command -v sha256sum >/dev/null 2>&1 ; then
--  shatool="sha256sum"
--elif command -v shasum >/dev/null 2>&1 ; then
--  shatool="shasum -a 256" # macOS fallback
--else
--  echo "Neither sha256sum nor shasum is available, cannot check hashes"
--fi
--
--# The calling script (usually appveyor.yml) can set a suffix to be used for
--# the tag and release name. This way it is possible to have a release for
--# the output of the CI/CD pipeline (marked as 'continuous') and also test
--# builds for other branches.
--# If this build was triggered by a tag, call the result a Release
--if [ ! -z "$UPLOADTOOL_SUFFIX" ] ; then
--  if [ "$UPLOADTOOL_SUFFIX" = "$APPVEYOR_REPO_TAG_NAME" ] ; then
--    RELEASE_NAME=$APPVEYOR_REPO_TAG_NAME
--    RELEASE_TITLE="Release build ($APPVEYOR_REPO_TAG_NAME)"
--    is_prerelease="false"
--  else
--    RELEASE_NAME="continuous-$UPLOADTOOL_SUFFIX"
--    RELEASE_TITLE="Continuous build ($UPLOADTOOL_SUFFIX)"
--    is_prerelease="true"
--  fi
--else
--  RELEASE_NAME="continuous-windows" # Do not use "latest" as it is reserved by GitHub
--  RELEASE_TITLE="Continuous build"
--  is_prerelease="true"
--fi
--
--#if [ "$TRAVIS_EVENT_TYPE" == "pull_request" ] ; then
--if [ -v APPVEYOR_PULL_REQUEST_NUMBER ]; then
--  echo "Release uploading disabled for pull requests, uploading to transfer.sh instead"
--  rm -f ./uploaded-to
--  for FILE in "$@" ; do
--    BASENAME="$(basename "${FILE}")"
--    curl -s -S --upload-file $FILE "https://transfer.sh/$BASENAME" > ./one-upload
--    echo "$(cat ./one-upload)" # this way we get a newline
--    echo -n "$(cat ./one-upload)\\n" >> ./uploaded-to # this way we get a \n but no newline
--  done
--#  review_url="https://api.github.com/repos/${APPVEYOR_REPO_NAME}/pulls/${APPVEYOR_PULL_REQUEST_NUMBER}/reviews"
--#  if [ -z $UPLOADTOOL_PR_BODY ] ; then
--#    body="Appveyor CI has created build artifacts for this PR here:"
--#  else
--#    body="$UPLOADTOOL_PR_BODY"
--#  fi
--#  body="$body\n$(cat ./uploaded-to)\nThe link(s) will expire 14 days from now."
--#  review_comment=$(curl -s -S -X POST \
--#    --header "Authorization: token ${GITHUB_TOKEN}" \
--#    --data '{"commit_id": "'"$APPVEYOR_REPO_COMMIT"'","body": "'"$body"'","event": "COMMENT"}' \
--#    $review_url)
--#  if echo $review_comment | grep -q "Bad credentials" 2>/dev/null ; then
--#    echo '"Bad credentials" response for --data {"commit_id": "'"$APPVEYOR_REPO_COMMIT"'","body": "'"$body"'","event": "COMMENT"}'
--#  fi
--  $shatool "$@"
--  exit 0
--fi
--
--if [ ! -z "$APPVEYOR_REPO_NAME" ] ; then
--  # We are running on Appveyor CI
--  echo "Running on Appveyor CI"
--  echo "APPVEYOR_REPO_COMMIT: $APPVEYOR_REPO_COMMIT"
--  REPO_SLUG="$APPVEYOR_REPO_NAME"
--  if [ -z "$GITHUB_TOKEN" ] ; then
--    echo "\$GITHUB_TOKEN missing."
--    echo "You can get one from https://github.com/settings/tokens."
--    echo "Minimal token scope is repo or public_repo to release on private or public repositories respectively."
--    echo "Then, either:"
--    echo "1. Encrypt it at https://ci.appveyor.com/tools/encrypt when logged into Appveyor account $APPVEYOR_ACCOUNT_NAME,"
--    echo "   then add a secure variable as described at https://www.appveyor.com/docs/build-configuration/#secure-variables"
--    echo "   to appveyor.yml."
--    echo "   The name of the variable should be GITHUB_TOKEN, and the value should be the encrypted value."
--    echo "OR"
--    echo "2. At https://ci.appveyor.com/project/$APPVEYOR_ACCOUNT_NAME/$APPVEYOR_PROJECT_SLUG/settings/environment"
--    echo "   add a new environmental variable with name GITHUB_TOKEN and the value of the unencrypted token from github."
--    echo "   Then hit the lock icon just to the right of the value so the token displays as a series of circles."
--    echo "   Only after the value shows as a series of circles hit the SAVE button at the bottom."
--    exit 1
--  fi
--else
--  # We are not running on Appveyor CI
--  echo "Not running on Appveyor CI"
--  if [ -z "$REPO_SLUG" ] ; then
--    read -r -s -p "Repo Slug (GitHub and Appveyor CI username/reponame): " REPO_SLUG
--  fi
--  if [ -z "$GITHUB_TOKEN" ] ; then
--    read -r -s -p "Token (https://github.com/settings/tokens): " GITHUB_TOKEN
--  fi
--fi
--
--tag_url="https://api.github.com/repos/$REPO_SLUG/git/refs/tags/$RELEASE_NAME"
--tag_infos=$(curl -s -S -XGET --header "Authorization: token ${GITHUB_TOKEN}" "${tag_url}")
--echo "tag_infos: $tag_infos"
--tag_sha=$(echo "$tag_infos" | grep '"sha":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "tag_sha: $tag_sha"
--
--release_url="https://api.github.com/repos/$REPO_SLUG/releases/tags/$RELEASE_NAME"
--echo "Getting the release ID..."
--echo "release_url: $release_url"
--release_infos=$(curl -s -S -XGET --header "Authorization: token ${GITHUB_TOKEN}" "${release_url}")
--echo "release_infos: $release_infos"
--release_id=$(echo "$release_infos" | grep "\"id\":" | head -n 1 | tr -s " " | cut -f 3 -d" " | cut -f 1 -d ",")
--echo "release ID: $release_id"
--upload_url=$(echo "$release_infos" | grep '"upload_url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "upload_url: $upload_url"
--release_url=$(echo "$release_infos" | grep '"url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "release_url: $release_url"
--target_commit_sha=$(echo "$release_infos" | grep '"target_commitish":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--echo "target_commit_sha: $target_commit_sha"
--
--if [ "$APPVEYOR_REPO_COMMIT" != "$target_commit_sha" ] ; then
--
--  echo "APPVEYOR_REPO_COMMIT != target_commit_sha, hence deleting $RELEASE_NAME..."
--  
--  if [ ! -z "$release_id" ]; then
--    delete_url="https://api.github.com/repos/$REPO_SLUG/releases/$release_id"
--    echo "Delete the release..."
--    echo "delete_url: $delete_url"
--    curl -s -S -XDELETE \
--        --header "Authorization: token ${GITHUB_TOKEN}" \
--        "${delete_url}"
--  fi
--
--  # echo "Checking if release with the same name is still there..."
--  # echo "release_url: $release_url"
--  # curl -s -S -XGET --header "Authorization: token ${GITHUB_TOKEN}" \
--  #     "$release_url"
--
--  if [ "$is_prerelease" = "true" ] ; then
--    # if this is a continuous build tag, then delete the old tag
--    # in preparation for the new release
--    echo "Delete the tag..."
--    delete_url="https://api.github.com/repos/$REPO_SLUG/git/refs/tags/$RELEASE_NAME"
--    echo "delete_url: $delete_url"
--    curl -s -S -XDELETE \
--        --header "Authorization: token ${GITHUB_TOKEN}" \
--        "${delete_url}"
--  fi
--
--  echo "Create release..."
--
--  if [ -z "$APPVEYOR_REPO_BRANCH" ] ; then
--    APPVEYOR_REPO_BRANCH="master"
--  fi
--
--  if [ ! -z "$APPVEYOR_JOB_ID" ] ; then
--    if [ -z "${UPLOADTOOL_BODY+x}" ] ; then
--      BODY="Appveyor CI build log: https://ci.appveyor.com/project/$APPVEYOR_ACCOUNT_NAME/$APPVEYOR_PROJECT_SLUG/build/$APPVEYOR_BUILD_VERSION"
--    else
--      BODY="$UPLOADTOOL_BODY"
--    fi
--  else
--    BODY="$UPLOADTOOL_BODY"
--  fi
--
--  release_infos=$(curl -s -S -H "Authorization: token ${GITHUB_TOKEN}" \
--       --data '{"tag_name": "'"$RELEASE_NAME"'","target_commitish": "'"$APPVEYOR_REPO_COMMIT"'","name": "'"$RELEASE_TITLE"'","body": "'"$BODY"'","draft": false,"prerelease": '$is_prerelease'}' "https://api.github.com/repos/$REPO_SLUG/releases")
--
--  echo "$release_infos"
--
--  unset upload_url
--  upload_url=$(echo "$release_infos" | grep '"upload_url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--  echo "upload_url: $upload_url"
--
--  unset release_url
--  release_url=$(echo "$release_infos" | grep '"url":' | head -n 1 | cut -d '"' -f 4 | cut -d '{' -f 1)
--  echo "release_url: $release_url"
--
--fi # if [ "$APPVEYOR_REPO_COMMIT" != "$tag_sha" ]
--
--if [ -z "$release_url" ] ; then
--      echo "Cannot figure out the release URL for $RELEASE_NAME"
--      exit 1
--fi
--
--echo "Upload binaries to the release..."
--
--for FILE in "$@" ; do
--  FULLNAME="${FILE}"
--  BASENAME="$(basename "${FILE}")"
--  curl -s -S -H "Authorization: token ${GITHUB_TOKEN}" \
--       -H "Accept: application/vnd.github.manifold-preview" \
--       -H "Content-Type: application/octet-stream" \
--       --data-binary @$FULLNAME \
--       "$upload_url?name=$BASENAME"
--  echo ""
--done
--
--$shatool "$@"
--
--if [ "$APPVEYOR_REPO_COMMIT" != "$tag_sha" ] ; then
--  echo "Publish the release..."
--
--  release_infos=$(curl -s -S -H "Authorization: token ${GITHUB_TOKEN}" \
--       --data '{"draft": false}' "$release_url")
--
--  echo "$release_infos"
--fi # if [ "$APPVEYOR_REPO_COMMIT" != "$tag_sha" ]
diff --cc zlib/.gitignore
index 793a921b3486baaa12417fb87288b73150200cf0,793a921b3486baaa12417fb87288b73150200cf0..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1 -1,1 +1,0 @@@
--/empty
diff --cc zlib/ChangeLog
index 30199a65a03daa6cdd55391a041d70fef5f19002,30199a65a03daa6cdd55391a041d70fef5f19002..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1515 -1,1515 +1,0 @@@
--
--                ChangeLog file for zlib
--
--Changes in 1.2.11 (15 Jan 2017)
--- Fix deflate stored bug when pulling last block from window
--- Permit immediate deflateParams changes before any deflate input
--
--Changes in 1.2.10 (2 Jan 2017)
--- Avoid warnings on snprintf() return value
--- Fix bug in deflate_stored() for zero-length input
--- Fix bug in gzwrite.c that produced corrupt gzip files
--- Remove files to be installed before copying them in Makefile.in
--- Add warnings when compiling with assembler code
--
--Changes in 1.2.9 (31 Dec 2016)
--- Fix contrib/minizip to permit unzipping with desktop API [Zouzou]
--- Improve contrib/blast to return unused bytes
--- Assure that gzoffset() is correct when appending
--- Improve compress() and uncompress() to support large lengths
--- Fix bug in test/example.c where error code not saved
--- Remedy Coverity warning [Randers-Pehrson]
--- Improve speed of gzprintf() in transparent mode
--- Fix inflateInit2() bug when windowBits is 16 or 32
--- Change DEBUG macro to ZLIB_DEBUG
--- Avoid uninitialized access by gzclose_w()
--- Allow building zlib outside of the source directory
--- Fix bug that accepted invalid zlib header when windowBits is zero
--- Fix gzseek() problem on MinGW due to buggy _lseeki64 there
--- Loop on write() calls in gzwrite.c in case of non-blocking I/O
--- Add --warn (-w) option to ./configure for more compiler warnings
--- Reject a window size of 256 bytes if not using the zlib wrapper
--- Fix bug when level 0 used with Z_HUFFMAN or Z_RLE
--- Add --debug (-d) option to ./configure to define ZLIB_DEBUG
--- Fix bugs in creating a very large gzip header
--- Add uncompress2() function, which returns the input size used
--- Assure that deflateParams() will not switch functions mid-block
--- Dramatically speed up deflation for level 0 (storing)
--- Add gzfread(), duplicating the interface of fread()
--- Add gzfwrite(), duplicating the interface of fwrite()
--- Add deflateGetDictionary() function
--- Use snprintf() for later versions of Microsoft C
--- Fix *Init macros to use z_ prefix when requested
--- Replace as400 with os400 for OS/400 support [Monnerat]
--- Add crc32_z() and adler32_z() functions with size_t lengths
--- Update Visual Studio project files [AraHaan]
--
--Changes in 1.2.8 (28 Apr 2013)
--- Update contrib/minizip/iowin32.c for Windows RT [Vollant]
--- Do not force Z_CONST for C++
--- Clean up contrib/vstudio [Roß]
--- Correct spelling error in zlib.h
--- Fix mixed line endings in contrib/vstudio
--
--Changes in 1.2.7.3 (13 Apr 2013)
--- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc
--
--Changes in 1.2.7.2 (13 Apr 2013)
--- Change check for a four-byte type back to hexadecimal
--- Fix typo in win32/Makefile.msc
--- Add casts in gzwrite.c for pointer differences
--
--Changes in 1.2.7.1 (24 Mar 2013)
--- Replace use of unsafe string functions with snprintf if available
--- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink]
--- Fix gzgetc undefine when Z_PREFIX set [Turk]
--- Eliminate use of mktemp in Makefile (not always available)
--- Fix bug in 'F' mode for gzopen()
--- Add inflateGetDictionary() function
--- Correct comment in deflate.h
--- Use _snprintf for snprintf in Microsoft C
--- On Darwin, only use /usr/bin/libtool if libtool is not Apple
--- Delete "--version" file if created by "ar --version" [Richard G.]
--- Fix configure check for veracity of compiler error return codes
--- Fix CMake compilation of static lib for MSVC2010 x64
--- Remove unused variable in infback9.c
--- Fix argument checks in gzlog_compress() and gzlog_write()
--- Clean up the usage of z_const and respect const usage within zlib
--- Clean up examples/gzlog.[ch] comparisons of different types
--- Avoid shift equal to bits in type (caused endless loop)
--- Fix uninitialized value bug in gzputc() introduced by const patches
--- Fix memory allocation error in examples/zran.c [Nor]
--- Fix bug where gzopen(), gzclose() would write an empty file
--- Fix bug in gzclose() when gzwrite() runs out of memory
--- Check for input buffer malloc failure in examples/gzappend.c
--- Add note to contrib/blast to use binary mode in stdio
--- Fix comparisons of differently signed integers in contrib/blast
--- Check for invalid code length codes in contrib/puff
--- Fix serious but very rare decompression bug in inftrees.c
--- Update inflateBack() comments, since inflate() can be faster
--- Use underscored I/O function names for WINAPI_FAMILY
--- Add _tr_flush_bits to the external symbols prefixed by --zprefix
--- Add contrib/vstudio/vc10 pre-build step for static only
--- Quote --version-script argument in CMakeLists.txt
--- Don't specify --version-script on Apple platforms in CMakeLists.txt
--- Fix casting error in contrib/testzlib/testzlib.c
--- Fix types in contrib/minizip to match result of get_crc_table()
--- Simplify contrib/vstudio/vc10 with 'd' suffix
--- Add TOP support to win32/Makefile.msc
--- Suport i686 and amd64 assembler builds in CMakeLists.txt
--- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h
--- Add vc11 and vc12 build files to contrib/vstudio
--- Add gzvprintf() as an undocumented function in zlib
--- Fix configure for Sun shell
--- Remove runtime check in configure for four-byte integer type
--- Add casts and consts to ease user conversion to C++
--- Add man pages for minizip and miniunzip
--- In Makefile uninstall, don't rm if preceding cd fails
--- Do not return Z_BUF_ERROR if deflateParam() has nothing to write
--
--Changes in 1.2.7 (2 May 2012)
--- Replace use of memmove() with a simple copy for portability
--- Test for existence of strerror
--- Restore gzgetc_ for backward compatibility with 1.2.6
--- Fix build with non-GNU make on Solaris
--- Require gcc 4.0 or later on Mac OS X to use the hidden attribute
--- Include unistd.h for Watcom C
--- Use __WATCOMC__ instead of __WATCOM__
--- Do not use the visibility attribute if NO_VIZ defined
--- Improve the detection of no hidden visibility attribute
--- Avoid using __int64 for gcc or solo compilation
--- Cast to char * in gzprintf to avoid warnings [Zinser]
--- Fix make_vms.com for VAX [Zinser]
--- Don't use library or built-in byte swaps
--- Simplify test and use of gcc hidden attribute
--- Fix bug in gzclose_w() when gzwrite() fails to allocate memory
--- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen()
--- Fix bug in test/minigzip.c for configure --solo
--- Fix contrib/vstudio project link errors [Mohanathas]
--- Add ability to choose the builder in make_vms.com [Schweda]
--- Add DESTDIR support to mingw32 win32/Makefile.gcc
--- Fix comments in win32/Makefile.gcc for proper usage
--- Allow overriding the default install locations for cmake
--- Generate and install the pkg-config file with cmake
--- Build both a static and a shared version of zlib with cmake
--- Include version symbols for cmake builds
--- If using cmake with MSVC, add the source directory to the includes
--- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta]
--- Move obsolete emx makefile to old [Truta]
--- Allow the use of -Wundef when compiling or using zlib
--- Avoid the use of the -u option with mktemp
--- Improve inflate() documentation on the use of Z_FINISH
--- Recognize clang as gcc
--- Add gzopen_w() in Windows for wide character path names
--- Rename zconf.h in CMakeLists.txt to move it out of the way
--- Add source directory in CMakeLists.txt for building examples
--- Look in build directory for zlib.pc in CMakeLists.txt
--- Remove gzflags from zlibvc.def in vc9 and vc10
--- Fix contrib/minizip compilation in the MinGW environment
--- Update ./configure for Solaris, support --64 [Mooney]
--- Remove -R. from Solaris shared build (possible security issue)
--- Avoid race condition for parallel make (-j) running example
--- Fix type mismatch between get_crc_table() and crc_table
--- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler]
--- Fix the path to zlib.map in CMakeLists.txt
--- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe]
--- Add instructions to win32/Makefile.gcc for shared install [Torri]
--
--Changes in 1.2.6.1 (12 Feb 2012)
--- Avoid the use of the Objective-C reserved name "id"
--- Include io.h in gzguts.h for Microsoft compilers
--- Fix problem with ./configure --prefix and gzgetc macro
--- Include gz_header definition when compiling zlib solo
--- Put gzflags() functionality back in zutil.c
--- Avoid library header include in crc32.c for Z_SOLO
--- Use name in GCC_CLASSIC as C compiler for coverage testing, if set
--- Minor cleanup in contrib/minizip/zip.c [Vollant]
--- Update make_vms.com [Zinser]
--- Remove unnecessary gzgetc_ function
--- Use optimized byte swap operations for Microsoft and GNU [Snyder]
--- Fix minor typo in zlib.h comments [Rzesniowiecki]
--
--Changes in 1.2.6 (29 Jan 2012)
--- Update the Pascal interface in contrib/pascal
--- Fix function numbers for gzgetc_ in zlibvc.def files
--- Fix configure.ac for contrib/minizip [Schiffer]
--- Fix large-entry detection in minizip on 64-bit systems [Schiffer]
--- Have ./configure use the compiler return code for error indication
--- Fix CMakeLists.txt for cross compilation [McClure]
--- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes]
--- Fix compilation of contrib/minizip on FreeBSD [Marquez]
--- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath]
--- Include io.h for Turbo C / Borland C on all platforms [Truta]
--- Make version explicit in contrib/minizip/configure.ac [Bosmans]
--- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant]
--- Minor cleanup up contrib/minizip/unzip.c [Vollant]
--- Fix bug when compiling minizip with C++ [Vollant]
--- Protect for long name and extra fields in contrib/minizip [Vollant]
--- Avoid some warnings in contrib/minizip [Vollant]
--- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip
--- Add missing libs to minizip linker command
--- Add support for VPATH builds in contrib/minizip
--- Add an --enable-demos option to contrib/minizip/configure
--- Add the generation of configure.log by ./configure
--- Exit when required parameters not provided to win32/Makefile.gcc
--- Have gzputc return the character written instead of the argument
--- Use the -m option on ldconfig for BSD systems [Tobias]
--- Correct in zlib.map when deflateResetKeep was added
--
--Changes in 1.2.5.3 (15 Jan 2012)
--- Restore gzgetc function for binary compatibility
--- Do not use _lseeki64 under Borland C++ [Truta]
--- Update win32/Makefile.msc to build test/*.c [Truta]
--- Remove old/visualc6 given CMakefile and other alternatives
--- Update AS400 build files and documentation [Monnerat]
--- Update win32/Makefile.gcc to build test/*.c [Truta]
--- Permit stronger flushes after Z_BLOCK flushes
--- Avoid extraneous empty blocks when doing empty flushes
--- Permit Z_NULL arguments to deflatePending
--- Allow deflatePrime() to insert bits in the middle of a stream
--- Remove second empty static block for Z_PARTIAL_FLUSH
--- Write out all of the available bits when using Z_BLOCK
--- Insert the first two strings in the hash table after a flush
--
--Changes in 1.2.5.2 (17 Dec 2011)
--- fix ld error: unable to find version dependency 'ZLIB_1.2.5'
--- use relative symlinks for shared libs
--- Avoid searching past window for Z_RLE strategy
--- Assure that high-water mark initialization is always applied in deflate
--- Add assertions to fill_window() in deflate.c to match comments
--- Update python link in README
--- Correct spelling error in gzread.c
--- Fix bug in gzgets() for a concatenated empty gzip stream
--- Correct error in comment for gz_make()
--- Change gzread() and related to ignore junk after gzip streams
--- Allow gzread() and related to continue after gzclearerr()
--- Allow gzrewind() and gzseek() after a premature end-of-file
--- Simplify gzseek() now that raw after gzip is ignored
--- Change gzgetc() to a macro for speed (~40% speedup in testing)
--- Fix gzclose() to return the actual error last encountered
--- Always add large file support for windows
--- Include zconf.h for windows large file support
--- Include zconf.h.cmakein for windows large file support
--- Update zconf.h.cmakein on make distclean
--- Merge vestigial vsnprintf determination from zutil.h to gzguts.h
--- Clarify how gzopen() appends in zlib.h comments
--- Correct documentation of gzdirect() since junk at end now ignored
--- Add a transparent write mode to gzopen() when 'T' is in the mode
--- Update python link in zlib man page
--- Get inffixed.h and MAKEFIXED result to match
--- Add a ./config --solo option to make zlib subset with no library use
--- Add undocumented inflateResetKeep() function for CAB file decoding
--- Add --cover option to ./configure for gcc coverage testing
--- Add #define ZLIB_CONST option to use const in the z_stream interface
--- Add comment to gzdopen() in zlib.h to use dup() when using fileno()
--- Note behavior of uncompress() to provide as much data as it can
--- Add files in contrib/minizip to aid in building libminizip
--- Split off AR options in Makefile.in and configure
--- Change ON macro to Z_ARG to avoid application conflicts
--- Facilitate compilation with Borland C++ for pragmas and vsnprintf
--- Include io.h for Turbo C / Borland C++
--- Move example.c and minigzip.c to test/
--- Simplify incomplete code table filling in inflate_table()
--- Remove code from inflate.c and infback.c that is impossible to execute
--- Test the inflate code with full coverage
--- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw)
--- Add deflateResetKeep and fix inflateResetKeep to retain dictionary
--- Fix gzwrite.c to accommodate reduced memory zlib compilation
--- Have inflate() with Z_FINISH avoid the allocation of a window
--- Do not set strm->adler when doing raw inflate
--- Fix gzeof() to behave just like feof() when read is not past end of file
--- Fix bug in gzread.c when end-of-file is reached
--- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF
--- Document gzread() capability to read concurrently written files
--- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo]
--
--Changes in 1.2.5.1 (10 Sep 2011)
--- Update FAQ entry on shared builds (#13)
--- Avoid symbolic argument to chmod in Makefile.in
--- Fix bug and add consts in contrib/puff [Oberhumer]
--- Update contrib/puff/zeros.raw test file to have all block types
--- Add full coverage test for puff in contrib/puff/Makefile
--- Fix static-only-build install in Makefile.in
--- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno]
--- Add libz.a dependency to shared in Makefile.in for parallel builds
--- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out
--- Replace $(...) with `...` in configure for non-bash sh [Bowler]
--- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen]
--- Add solaris* to Linux* in configure to allow gcc use [Groffen]
--- Add *bsd* to Linux* case in configure [Bar-Lev]
--- Add inffast.obj to dependencies in win32/Makefile.msc
--- Correct spelling error in deflate.h [Kohler]
--- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc
--- Add test to configure for GNU C looking for gcc in output of $cc -v
--- Add zlib.pc generation to win32/Makefile.gcc [Weigelt]
--- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not
--- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense
--- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser)
--- Make stronger test in zconf.h to include unistd.h for LFS
--- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack]
--- Fix zlib.h LFS support when Z_PREFIX used
--- Add updated as400 support (removed from old) [Monnerat]
--- Avoid deflate sensitivity to volatile input data
--- Avoid division in adler32_combine for NO_DIVIDE
--- Clarify the use of Z_FINISH with deflateBound() amount of space
--- Set binary for output file in puff.c
--- Use u4 type for crc_table to avoid conversion warnings
--- Apply casts in zlib.h to avoid conversion warnings
--- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller]
--- Improve inflateSync() documentation to note indeterminancy
--- Add deflatePending() function to return the amount of pending output
--- Correct the spelling of "specification" in FAQ [Randers-Pehrson]
--- Add a check in configure for stdarg.h, use for gzprintf()
--- Check that pointers fit in ints when gzprint() compiled old style
--- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler]
--- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt]
--- Add debug records in assmebler code [Londer]
--- Update RFC references to use http://tools.ietf.org/html/... [Li]
--- Add --archs option, use of libtool to configure for Mac OS X [Borstel]
--
--Changes in 1.2.5 (19 Apr 2010)
--- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev]
--- Default to libdir as sharedlibdir in configure [Nieder]
--- Update copyright dates on modified source files
--- Update trees.c to be able to generate modified trees.h
--- Exit configure for MinGW, suggesting win32/Makefile.gcc
--- Check for NULL path in gz_open [Homurlu]
--
--Changes in 1.2.4.5 (18 Apr 2010)
--- Set sharedlibdir in configure [Torok]
--- Set LDFLAGS in Makefile.in [Bar-Lev]
--- Avoid mkdir objs race condition in Makefile.in [Bowler]
--- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays
--- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C
--- Don't use hidden attribute when it is a warning generator (e.g. Solaris)
--
--Changes in 1.2.4.4 (18 Apr 2010)
--- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok]
--- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty
--- Try to use bash or ksh regardless of functionality of /bin/sh
--- Fix configure incompatibility with NetBSD sh
--- Remove attempt to run under bash or ksh since have better NetBSD fix
--- Fix win32/Makefile.gcc for MinGW [Bar-Lev]
--- Add diagnostic messages when using CROSS_PREFIX in configure
--- Added --sharedlibdir option to configure [Weigelt]
--- Use hidden visibility attribute when available [Frysinger]
--
--Changes in 1.2.4.3 (10 Apr 2010)
--- Only use CROSS_PREFIX in configure for ar and ranlib if they exist
--- Use CROSS_PREFIX for nm [Bar-Lev]
--- Assume _LARGEFILE64_SOURCE defined is equivalent to true
--- Avoid use of undefined symbols in #if with && and ||
--- Make *64 prototypes in gzguts.h consistent with functions
--- Add -shared load option for MinGW in configure [Bowler]
--- Move z_off64_t to public interface, use instead of off64_t
--- Remove ! from shell test in configure (not portable to Solaris)
--- Change +0 macro tests to -0 for possibly increased portability
--
--Changes in 1.2.4.2 (9 Apr 2010)
--- Add consistent carriage returns to readme.txt's in masmx86 and masmx64
--- Really provide prototypes for *64 functions when building without LFS
--- Only define unlink() in minigzip.c if unistd.h not included
--- Update README to point to contrib/vstudio project files
--- Move projects/vc6 to old/ and remove projects/
--- Include stdlib.h in minigzip.c for setmode() definition under WinCE
--- Clean up assembler builds in win32/Makefile.msc [Rowe]
--- Include sys/types.h for Microsoft for off_t definition
--- Fix memory leak on error in gz_open()
--- Symbolize nm as $NM in configure [Weigelt]
--- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt]
--- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined
--- Fix bug in gzeof() to take into account unused input data
--- Avoid initialization of structures with variables in puff.c
--- Updated win32/README-WIN32.txt [Rowe]
--
--Changes in 1.2.4.1 (28 Mar 2010)
--- Remove the use of [a-z] constructs for sed in configure [gentoo 310225]
--- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech]
--- Restore "for debugging" comment on sprintf() in gzlib.c
--- Remove fdopen for MVS from gzguts.h
--- Put new README-WIN32.txt in win32 [Rowe]
--- Add check for shell to configure and invoke another shell if needed
--- Fix big fat stinking bug in gzseek() on uncompressed files
--- Remove vestigial F_OPEN64 define in zutil.h
--- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE
--- Avoid errors on non-LFS systems when applications define LFS macros
--- Set EXE to ".exe" in configure for MINGW [Kahle]
--- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill]
--- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev]
--- Add DLL install in win32/makefile.gcc [Bar-Lev]
--- Allow Linux* or linux* from uname in configure [Bar-Lev]
--- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev]
--- Add cross-compilation prefixes to configure [Bar-Lev]
--- Match type exactly in gz_load() invocation in gzread.c
--- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func
--- Provide prototypes for *64 functions when building zlib without LFS
--- Don't use -lc when linking shared library on MinGW
--- Remove errno.h check in configure and vestigial errno code in zutil.h
--
--Changes in 1.2.4 (14 Mar 2010)
--- Fix VER3 extraction in configure for no fourth subversion
--- Update zlib.3, add docs to Makefile.in to make .pdf out of it
--- Add zlib.3.pdf to distribution
--- Don't set error code in gzerror() if passed pointer is NULL
--- Apply destination directory fixes to CMakeLists.txt [Lowman]
--- Move #cmakedefine's to a new zconf.in.cmakein
--- Restore zconf.h for builds that don't use configure or cmake
--- Add distclean to dummy Makefile for convenience
--- Update and improve INDEX, README, and FAQ
--- Update CMakeLists.txt for the return of zconf.h [Lowman]
--- Update contrib/vstudio/vc9 and vc10 [Vollant]
--- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc
--- Apply license and readme changes to contrib/asm686 [Raiter]
--- Check file name lengths and add -c option in minigzip.c [Li]
--- Update contrib/amd64 and contrib/masmx86/ [Vollant]
--- Avoid use of "eof" parameter in trees.c to not shadow library variable
--- Update make_vms.com for removal of zlibdefs.h [Zinser]
--- Update assembler code and vstudio projects in contrib [Vollant]
--- Remove outdated assembler code contrib/masm686 and contrib/asm586
--- Remove old vc7 and vc8 from contrib/vstudio
--- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe]
--- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open()
--- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant]
--- Remove *64 functions from win32/zlib.def (they're not 64-bit yet)
--- Fix bug in void-returning vsprintf() case in gzwrite.c
--- Fix name change from inflate.h in contrib/inflate86/inffas86.c
--- Check if temporary file exists before removing in make_vms.com [Zinser]
--- Fix make install and uninstall for --static option
--- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta]
--- Update readme.txt in contrib/masmx64 and masmx86 to assemble
--
--Changes in 1.2.3.9 (21 Feb 2010)
--- Expunge gzio.c
--- Move as400 build information to old
--- Fix updates in contrib/minizip and contrib/vstudio
--- Add const to vsnprintf test in configure to avoid warnings [Weigelt]
--- Delete zconf.h (made by configure) [Weigelt]
--- Change zconf.in.h to zconf.h.in per convention [Weigelt]
--- Check for NULL buf in gzgets()
--- Return empty string for gzgets() with len == 1 (like fgets())
--- Fix description of gzgets() in zlib.h for end-of-file, NULL return
--- Update minizip to 1.1 [Vollant]
--- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c
--- Note in zlib.h that gzerror() should be used to distinguish from EOF
--- Remove use of snprintf() from gzlib.c
--- Fix bug in gzseek()
--- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant]
--- Fix zconf.h generation in CMakeLists.txt [Lowman]
--- Improve comments in zconf.h where modified by configure
--
--Changes in 1.2.3.8 (13 Feb 2010)
--- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
--- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
--- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
--- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
--- Fix missing error return in gzflush(), add zlib.h note
--- Add *64 functions to zlib.map [Levin]
--- Fix signed/unsigned comparison in gz_comp()
--- Use SFLAGS when testing shared linking in configure
--- Add --64 option to ./configure to use -m64 with gcc
--- Fix ./configure --help to correctly name options
--- Have make fail if a test fails [Levin]
--- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
--- Remove assembler object files from contrib
--
--Changes in 1.2.3.7 (24 Jan 2010)
--- Always gzopen() with O_LARGEFILE if available
--- Fix gzdirect() to work immediately after gzopen() or gzdopen()
--- Make gzdirect() more precise when the state changes while reading
--- Improve zlib.h documentation in many places
--- Catch memory allocation failure in gz_open()
--- Complete close operation if seek forward in gzclose_w() fails
--- Return Z_ERRNO from gzclose_r() if close() fails
--- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
--- Return zero for gzwrite() errors to match zlib.h description
--- Return -1 on gzputs() error to match zlib.h description
--- Add zconf.in.h to allow recovery from configure modification [Weigelt]
--- Fix static library permissions in Makefile.in [Weigelt]
--- Avoid warnings in configure tests that hide functionality [Weigelt]
--- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
--- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
--- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
--- Keep object files in subdirectories to reduce the clutter somewhat
--- Remove default Makefile and zlibdefs.h, add dummy Makefile
--- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
--- Remove zlibdefs.h completely -- modify zconf.h instead
--
--Changes in 1.2.3.6 (17 Jan 2010)
--- Avoid void * arithmetic in gzread.c and gzwrite.c
--- Make compilers happier with const char * for gz_error message
--- Avoid unused parameter warning in inflate.c
--- Avoid signed-unsigned comparison warning in inflate.c
--- Indent #pragma's for traditional C
--- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
--- Correct email address in configure for system options
--- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
--- Update zlib.map [Brown]
--- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok]
--- Apply various fixes to CMakeLists.txt [Lowman]
--- Add checks on len in gzread() and gzwrite()
--- Add error message for no more room for gzungetc()
--- Remove zlib version check in gzwrite()
--- Defer compression of gzprintf() result until need to
--- Use snprintf() in gzdopen() if available
--- Remove USE_MMAP configuration determination (only used by minigzip)
--- Remove examples/pigz.c (available separately)
--- Update examples/gun.c to 1.6
--
--Changes in 1.2.3.5 (8 Jan 2010)
--- Add space after #if in zutil.h for some compilers
--- Fix relatively harmless bug in deflate_fast() [Exarevsky]
--- Fix same problem in deflate_slow()
--- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
--- Add deflate_rle() for faster Z_RLE strategy run-length encoding
--- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
--- Change name of "write" variable in inffast.c to avoid library collisions
--- Fix premature EOF from gzread() in gzio.c [Brown]
--- Use zlib header window size if windowBits is 0 in inflateInit2()
--- Remove compressBound() call in deflate.c to avoid linking compress.o
--- Replace use of errno in gz* with functions, support WinCE [Alves]
--- Provide alternative to perror() in minigzip.c for WinCE [Alves]
--- Don't use _vsnprintf on later versions of MSVC [Lowman]
--- Add CMake build script and input file [Lowman]
--- Update contrib/minizip to 1.1 [Svensson, Vollant]
--- Moved nintendods directory from contrib to .
--- Replace gzio.c with a new set of routines with the same functionality
--- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
--- Update contrib/minizip to 1.1b
--- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
--
--Changes in 1.2.3.4 (21 Dec 2009)
--- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
--- Update comments in configure and Makefile.in for default --shared
--- Fix test -z's in configure [Marquess]
--- Build examplesh and minigzipsh when not testing
--- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
--- Import LDFLAGS from the environment in configure
--- Fix configure to populate SFLAGS with discovered CFLAGS options
--- Adapt make_vms.com to the new Makefile.in [Zinser]
--- Add zlib2ansi script for C++ compilation [Marquess]
--- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
--- Add AMD64 assembler code for longest match to contrib [Teterin]
--- Include options from $SFLAGS when doing $LDSHARED
--- Simplify 64-bit file support by introducing z_off64_t type
--- Make shared object files in objs directory to work around old Sun cc
--- Use only three-part version number for Darwin shared compiles
--- Add rc option to ar in Makefile.in for when ./configure not run
--- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
--- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
--- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
--- Rename Makefile.in targets allstatic to static and allshared to shared
--- Fix static and shared Makefile.in targets to be independent
--- Correct error return bug in gz_open() by setting state [Brown]
--- Put spaces before ;;'s in configure for better sh compatibility
--- Add pigz.c (parallel implementation of gzip) to examples/
--- Correct constant in crc32.c to UL [Leventhal]
--- Reject negative lengths in crc32_combine()
--- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
--- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
--- Correct typo in doc/algorithm.txt [Janik]
--- Fix bug in adler32_combine() [Zhu]
--- Catch missing-end-of-block-code error in all inflates and in puff
--    Assures that random input to inflate eventually results in an error
--- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
--- Update ENOUGH and its usage to reflect discovered bounds
--- Fix gzerror() error report on empty input file [Brown]
--- Add ush casts in trees.c to avoid pedantic runtime errors
--- Fix typo in zlib.h uncompress() description [Reiss]
--- Correct inflate() comments with regard to automatic header detection
--- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
--- Put new version of gzlog (2.0) in examples with interruption recovery
--- Add puff compile option to permit invalid distance-too-far streams
--- Add puff TEST command options, ability to read piped input
--- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
--  _LARGEFILE64_SOURCE not defined
--- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
--- Fix deflateSetDictionary() to use all 32K for output consistency
--- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
--- Clear bytes after deflate lookahead to avoid use of uninitialized data
--- Change a limit in inftrees.c to be more transparent to Coverity Prevent
--- Update win32/zlib.def with exported symbols from zlib.h
--- Correct spelling errors in zlib.h [Willem, Sobrado]
--- Allow Z_BLOCK for deflate() to force a new block
--- Allow negative bits in inflatePrime() to delete existing bit buffer
--- Add Z_TREES flush option to inflate() to return at end of trees
--- Add inflateMark() to return current state information for random access
--- Add Makefile for NintendoDS to contrib [Costa]
--- Add -w in configure compile tests to avoid spurious warnings [Beucler]
--- Fix typos in zlib.h comments for deflateSetDictionary()
--- Fix EOF detection in transparent gzread() [Maier]
--
--Changes in 1.2.3.3 (2 October 2006)
--- Make --shared the default for configure, add a --static option
--- Add compile option to permit invalid distance-too-far streams
--- Add inflateUndermine() function which is required to enable above
--- Remove use of "this" variable name for C++ compatibility [Marquess]
--- Add testing of shared library in make test, if shared library built
--- Use ftello() and fseeko() if available instead of ftell() and fseek()
--- Provide two versions of all functions that use the z_off_t type for
--  binary compatibility -- a normal version and a 64-bit offset version,
--  per the Large File Support Extension when _LARGEFILE64_SOURCE is
--  defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
--  is defined to be 64
--- Add a --uname= option to configure to perhaps help with cross-compiling
--
--Changes in 1.2.3.2 (3 September 2006)
--- Turn off silly Borland warnings [Hay]
--- Use off64_t and define _LARGEFILE64_SOURCE when present
--- Fix missing dependency on inffixed.h in Makefile.in
--- Rig configure --shared to build both shared and static [Teredesai, Truta]
--- Remove zconf.in.h and instead create a new zlibdefs.h file
--- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
--- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
--
--Changes in 1.2.3.1 (16 August 2006)
--- Add watcom directory with OpenWatcom make files [Daniel]
--- Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
--- Update make_vms.com [Zinser]
--- Use -fPIC for shared build in configure [Teredesai, Nicholson]
--- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen]
--- Use fdopen() (not _fdopen()) for Interix in zutil.h [Bäck]
--- Add some FAQ entries about the contrib directory
--- Update the MVS question in the FAQ
--- Avoid extraneous reads after EOF in gzio.c [Brown]
--- Correct spelling of "successfully" in gzio.c [Randers-Pehrson]
--- Add comments to zlib.h about gzerror() usage [Brown]
--- Set extra flags in gzip header in gzopen() like deflate() does
--- Make configure options more compatible with double-dash conventions
--  [Weigelt]
--- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen]
--- Fix uninstall target in Makefile.in [Truta]
--- Add pkgconfig support [Weigelt]
--- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt]
--- Replace set_data_type() with a more accurate detect_data_type() in
--  trees.c, according to the txtvsbin.txt document [Truta]
--- Swap the order of #include <stdio.h> and #include "zlib.h" in
--  gzio.c, example.c and minigzip.c [Truta]
--- Shut up annoying VS2005 warnings about standard C deprecation [Rowe,
--  Truta] (where?)
--- Fix target "clean" from win32/Makefile.bor [Truta]
--- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe]
--- Update zlib www home address in win32/DLL_FAQ.txt [Truta]
--- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove]
--- Enable browse info in the "Debug" and "ASM Debug" configurations in
--  the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta]
--- Add pkgconfig support [Weigelt]
--- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h,
--  for use in win32/zlib1.rc [Polushin, Rowe, Truta]
--- Add a document that explains the new text detection scheme to
--  doc/txtvsbin.txt [Truta]
--- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta]
--- Move algorithm.txt into doc/ [Truta]
--- Synchronize FAQ with website
--- Fix compressBound(), was low for some pathological cases [Fearnley]
--- Take into account wrapper variations in deflateBound()
--- Set examples/zpipe.c input and output to binary mode for Windows
--- Update examples/zlib_how.html with new zpipe.c (also web site)
--- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
--  that gcc became pickier in 4.0)
--- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain
--  un-versioned, the patch adds versioning only for symbols introduced in
--  zlib-1.2.0 or later.  It also declares as local those symbols which are
--  not designed to be exported." [Levin]
--- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure
--- Do not initialize global static by default in trees.c, add a response
--  NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess]
--- Don't use strerror() in gzio.c under WinCE [Yakimov]
--- Don't use errno.h in zutil.h under WinCE [Yakimov]
--- Move arguments for AR to its usage to allow replacing ar [Marot]
--- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson]
--- Improve inflateInit() and inflateInit2() documentation
--- Fix structure size comment in inflate.h
--- Change configure help option from --h* to --help [Santos]
--
--Changes in 1.2.3 (18 July 2005)
--- Apply security vulnerability fixes to contrib/infback9 as well
--- Clean up some text files (carriage returns, trailing space)
--- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
--
--Changes in 1.2.2.4 (11 July 2005)
--- Add inflatePrime() function for starting inflation at bit boundary
--- Avoid some Visual C warnings in deflate.c
--- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
--  compile
--- Fix some spelling errors in comments [Betts]
--- Correct inflateInit2() error return documentation in zlib.h
--- Add zran.c example of compressed data random access to examples
--  directory, shows use of inflatePrime()
--- Fix cast for assignments to strm->state in inflate.c and infback.c
--- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
--- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
--- Add cast in trees.c t avoid a warning [Oberhumer]
--- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
--- Update make_vms.com [Zinser]
--- Initialize state->write in inflateReset() since copied in inflate_fast()
--- Be more strict on incomplete code sets in inflate_table() and increase
--  ENOUGH and MAXD -- this repairs a possible security vulnerability for
--  invalid inflate input.  Thanks to Tavis Ormandy and Markus Oberhumer for
--  discovering the vulnerability and providing test cases.
--- Add ia64 support to configure for HP-UX [Smith]
--- Add error return to gzread() for format or i/o error [Levin]
--- Use malloc.h for OS/2 [Necasek]
--
--Changes in 1.2.2.3 (27 May 2005)
--- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
--- Typecast fread() return values in gzio.c [Vollant]
--- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
--- Fix crc check bug in gzread() after gzungetc() [Heiner]
--- Add the deflateTune() function to adjust internal compression parameters
--- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
--- Remove an incorrect assertion in examples/zpipe.c
--- Add C++ wrapper in infback9.h [Donais]
--- Fix bug in inflateCopy() when decoding fixed codes
--- Note in zlib.h how much deflateSetDictionary() actually uses
--- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
--- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
--- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
--- Add gzdirect() function to indicate transparent reads
--- Update contrib/minizip [Vollant]
--- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
--- Add casts in crc32.c to avoid warnings [Oberhumer]
--- Add contrib/masmx64 [Vollant]
--- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
--
--Changes in 1.2.2.2 (30 December 2004)
--- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
--  avoid implicit memcpy calls (portability for no-library compilation)
--- Increase sprintf() buffer size in gzdopen() to allow for large numbers
--- Add INFLATE_STRICT to check distances against zlib header
--- Improve WinCE errno handling and comments [Chang]
--- Remove comment about no gzip header processing in FAQ
--- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
--- Add updated make_vms.com [Coghlan], update README
--- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
--  fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
--- Add FAQ entry and comments in deflate.c on uninitialized memory access
--- Add Solaris 9 make options in configure [Gilbert]
--- Allow strerror() usage in gzio.c for STDC
--- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
--- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
--- Use z_off_t for adler32_combine() and crc32_combine() lengths
--- Make adler32() much faster for small len
--- Use OS_CODE in deflate() default gzip header
--
--Changes in 1.2.2.1 (31 October 2004)
--- Allow inflateSetDictionary() call for raw inflate
--- Fix inflate header crc check bug for file names and comments
--- Add deflateSetHeader() and gz_header structure for custom gzip headers
--- Add inflateGetheader() to retrieve gzip headers
--- Add crc32_combine() and adler32_combine() functions
--- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
--- Use zstreamp consistently in zlib.h (inflate_back functions)
--- Remove GUNZIP condition from definition of inflate_mode in inflate.h
--  and in contrib/inflate86/inffast.S [Truta, Anderson]
--- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
--- Update projects/README.projects and projects/visualc6 [Truta]
--- Update win32/DLL_FAQ.txt [Truta]
--- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
--- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
--- Use a new algorithm for setting strm->data_type in trees.c [Truta]
--- Do not define an exit() prototype in zutil.c unless DEBUG defined
--- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
--- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
--- Fix Darwin build version identification [Peterson]
--
--Changes in 1.2.2 (3 October 2004)
--- Update zlib.h comments on gzip in-memory processing
--- Set adler to 1 in inflateReset() to support Java test suite [Walles]
--- Add contrib/dotzlib [Ravn]
--- Update win32/DLL_FAQ.txt [Truta]
--- Update contrib/minizip [Vollant]
--- Move contrib/visual-basic.txt to old/ [Truta]
--- Fix assembler builds in projects/visualc6/ [Truta]
--
--Changes in 1.2.1.2 (9 September 2004)
--- Update INDEX file
--- Fix trees.c to update strm->data_type (no one ever noticed!)
--- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
--- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
--- Add limited multitasking protection to DYNAMIC_CRC_TABLE
--- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
--- Don't declare strerror() under VMS [Mozilla]
--- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
--- Update contrib/ada [Anisimkov]
--- Update contrib/minizip [Vollant]
--- Fix configure to not hardcode directories for Darwin [Peterson]
--- Fix gzio.c to not return error on empty files [Brown]
--- Fix indentation; update version in contrib/delphi/ZLib.pas and
--  contrib/pascal/zlibpas.pas [Truta]
--- Update mkasm.bat in contrib/masmx86 [Truta]
--- Update contrib/untgz [Truta]
--- Add projects/README.projects [Truta]
--- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
--- Update win32/DLL_FAQ.txt [Truta]
--- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
--- Remove an unnecessary assignment to curr in inftrees.c [Truta]
--- Add OS/2 to exe builds in configure [Poltorak]
--- Remove err dummy parameter in zlib.h [Kientzle]
--
--Changes in 1.2.1.1 (9 January 2004)
--- Update email address in README
--- Several FAQ updates
--- Fix a big fat bug in inftrees.c that prevented decoding valid
--  dynamic blocks with only literals and no distance codes --
--  Thanks to "Hot Emu" for the bug report and sample file
--- Add a note to puff.c on no distance codes case.
--
--Changes in 1.2.1 (17 November 2003)
--- Remove a tab in contrib/gzappend/gzappend.c
--- Update some interfaces in contrib for new zlib functions
--- Update zlib version number in some contrib entries
--- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
--- Support shared libraries on Hurd and KFreeBSD [Brown]
--- Fix error in NO_DIVIDE option of adler32.c
--
--Changes in 1.2.0.8 (4 November 2003)
--- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
--- Add experimental NO_DIVIDE #define in adler32.c
--    - Possibly faster on some processors (let me know if it is)
--- Correct Z_BLOCK to not return on first inflate call if no wrap
--- Fix strm->data_type on inflate() return to correctly indicate EOB
--- Add deflatePrime() function for appending in the middle of a byte
--- Add contrib/gzappend for an example of appending to a stream
--- Update win32/DLL_FAQ.txt [Truta]
--- Delete Turbo C comment in README [Truta]
--- Improve some indentation in zconf.h [Truta]
--- Fix infinite loop on bad input in configure script [Church]
--- Fix gzeof() for concatenated gzip files [Johnson]
--- Add example to contrib/visual-basic.txt [Michael B.]
--- Add -p to mkdir's in Makefile.in [vda]
--- Fix configure to properly detect presence or lack of printf functions
--- Add AS400 support [Monnerat]
--- Add a little Cygwin support [Wilson]
--
--Changes in 1.2.0.7 (21 September 2003)
--- Correct some debug formats in contrib/infback9
--- Cast a type in a debug statement in trees.c
--- Change search and replace delimiter in configure from % to # [Beebe]
--- Update contrib/untgz to 0.2 with various fixes [Truta]
--- Add build support for Amiga [Nikl]
--- Remove some directories in old that have been updated to 1.2
--- Add dylib building for Mac OS X in configure and Makefile.in
--- Remove old distribution stuff from Makefile
--- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
--- Update links in README
--
--Changes in 1.2.0.6 (13 September 2003)
--- Minor FAQ updates
--- Update contrib/minizip to 1.00 [Vollant]
--- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
--- Update POSTINC comment for 68060 [Nikl]
--- Add contrib/infback9 with deflate64 decoding (unsupported)
--- For MVS define NO_vsnprintf and undefine FAR [van Burik]
--- Add pragma for fdopen on MVS [van Burik]
--
--Changes in 1.2.0.5 (8 September 2003)
--- Add OF to inflateBackEnd() declaration in zlib.h
--- Remember start when using gzdopen in the middle of a file
--- Use internal off_t counters in gz* functions to properly handle seeks
--- Perform more rigorous check for distance-too-far in inffast.c
--- Add Z_BLOCK flush option to return from inflate at block boundary
--- Set strm->data_type on return from inflate
--    - Indicate bits unused, if at block boundary, and if in last block
--- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
--- Add condition so old NO_DEFLATE define still works for compatibility
--- FAQ update regarding the Windows DLL [Truta]
--- INDEX update: add qnx entry, remove aix entry [Truta]
--- Install zlib.3 into mandir [Wilson]
--- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
--- Adapt the zlib interface to the new DLL convention guidelines [Truta]
--- Introduce ZLIB_WINAPI macro to allow the export of functions using
--  the WINAPI calling convention, for Visual Basic [Vollant, Truta]
--- Update msdos and win32 scripts and makefiles [Truta]
--- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
--- Add contrib/ada [Anisimkov]
--- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
--- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
--- Add contrib/masm686 [Truta]
--- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
--  [Truta, Vollant]
--- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
--- Remove contrib/delphi2; add a new contrib/delphi [Truta]
--- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
--  and fix some method prototypes [Truta]
--- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
--  [Truta]
--- Avoid the use of backslash (\) in contrib/minizip [Vollant]
--- Fix file time handling in contrib/untgz; update makefiles [Truta]
--- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
--  [Vollant]
--- Remove contrib/vstudio/vc15_16 [Vollant]
--- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
--- Update README.contrib [Truta]
--- Invert the assignment order of match_head and s->prev[...] in
--  INSERT_STRING [Truta]
--- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
--  [Truta]
--- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
--- Fix prototype of syncsearch in inflate.c [Truta]
--- Introduce ASMINF macro to be enabled when using an ASM implementation
--  of inflate_fast [Truta]
--- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
--- Modify test_gzio in example.c to take a single file name as a
--  parameter [Truta]
--- Exit the example.c program if gzopen fails [Truta]
--- Add type casts around strlen in example.c [Truta]
--- Remove casting to sizeof in minigzip.c; give a proper type
--  to the variable compared with SUFFIX_LEN [Truta]
--- Update definitions of STDC and STDC99 in zconf.h [Truta]
--- Synchronize zconf.h with the new Windows DLL interface [Truta]
--- Use SYS16BIT instead of __32BIT__ to distinguish between
--  16- and 32-bit platforms [Truta]
--- Use far memory allocators in small 16-bit memory models for
--  Turbo C [Truta]
--- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
--  zlibCompileFlags [Truta]
--- Cygwin has vsnprintf [Wilson]
--- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
--- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
--
--Changes in 1.2.0.4 (10 August 2003)
--- Minor FAQ updates
--- Be more strict when checking inflateInit2's windowBits parameter
--- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
--- Add gzip wrapper option to deflateInit2 using windowBits
--- Add updated QNX rule in configure and qnx directory [Bonnefoy]
--- Make inflate distance-too-far checks more rigorous
--- Clean up FAR usage in inflate
--- Add casting to sizeof() in gzio.c and minigzip.c
--
--Changes in 1.2.0.3 (19 July 2003)
--- Fix silly error in gzungetc() implementation [Vollant]
--- Update contrib/minizip and contrib/vstudio [Vollant]
--- Fix printf format in example.c
--- Correct cdecl support in zconf.in.h [Anisimkov]
--- Minor FAQ updates
--
--Changes in 1.2.0.2 (13 July 2003)
--- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
--- Attempt to avoid warnings in crc32.c for pointer-int conversion
--- Add AIX to configure, remove aix directory [Bakker]
--- Add some casts to minigzip.c
--- Improve checking after insecure sprintf() or vsprintf() calls
--- Remove #elif's from crc32.c
--- Change leave label to inf_leave in inflate.c and infback.c to avoid
--  library conflicts
--- Remove inflate gzip decoding by default--only enable gzip decoding by
--  special request for stricter backward compatibility
--- Add zlibCompileFlags() function to return compilation information
--- More typecasting in deflate.c to avoid warnings
--- Remove leading underscore from _Capital #defines [Truta]
--- Fix configure to link shared library when testing
--- Add some Windows CE target adjustments [Mai]
--- Remove #define ZLIB_DLL in zconf.h [Vollant]
--- Add zlib.3 [Rodgers]
--- Update RFC URL in deflate.c and algorithm.txt [Mai]
--- Add zlib_dll_FAQ.txt to contrib [Truta]
--- Add UL to some constants [Truta]
--- Update minizip and vstudio [Vollant]
--- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
--- Expand use of NO_DUMMY_DECL to avoid all dummy structures
--- Added iostream3 to contrib [Schwardt]
--- Replace rewind() with fseek() for WinCE [Truta]
--- Improve setting of zlib format compression level flags
--    - Report 0 for huffman and rle strategies and for level == 0 or 1
--    - Report 2 only for level == 6
--- Only deal with 64K limit when necessary at compile time [Truta]
--- Allow TOO_FAR check to be turned off at compile time [Truta]
--- Add gzclearerr() function [Souza]
--- Add gzungetc() function
--
--Changes in 1.2.0.1 (17 March 2003)
--- Add Z_RLE strategy for run-length encoding [Truta]
--    - When Z_RLE requested, restrict matches to distance one
--    - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
--- Correct FASTEST compilation to allow level == 0
--- Clean up what gets compiled for FASTEST
--- Incorporate changes to zconf.in.h [Vollant]
--    - Refine detection of Turbo C need for dummy returns
--    - Refine ZLIB_DLL compilation
--    - Include additional header file on VMS for off_t typedef
--- Try to use _vsnprintf where it supplants vsprintf [Vollant]
--- Add some casts in inffast.c
--- Enchance comments in zlib.h on what happens if gzprintf() tries to
--  write more than 4095 bytes before compression
--- Remove unused state from inflateBackEnd()
--- Remove exit(0) from minigzip.c, example.c
--- Get rid of all those darn tabs
--- Add "check" target to Makefile.in that does the same thing as "test"
--- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
--- Update contrib/inflate86 [Anderson]
--- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
--- Add msdos and win32 directories with makefiles [Truta]
--- More additions and improvements to the FAQ
--
--Changes in 1.2.0 (9 March 2003)
--- New and improved inflate code
--    - About 20% faster
--    - Does not allocate 32K window unless and until needed
--    - Automatically detects and decompresses gzip streams
--    - Raw inflate no longer needs an extra dummy byte at end
--    - Added inflateBack functions using a callback interface--even faster
--      than inflate, useful for file utilities (gzip, zip)
--    - Added inflateCopy() function to record state for random access on
--      externally generated deflate streams (e.g. in gzip files)
--    - More readable code (I hope)
--- New and improved crc32()
--    - About 50% faster, thanks to suggestions from Rodney Brown
--- Add deflateBound() and compressBound() functions
--- Fix memory leak in deflateInit2()
--- Permit setting dictionary for raw deflate (for parallel deflate)
--- Fix const declaration for gzwrite()
--- Check for some malloc() failures in gzio.c
--- Fix bug in gzopen() on single-byte file 0x1f
--- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
--  and next buffer doesn't start with 0x8b
--- Fix uncompress() to return Z_DATA_ERROR on truncated input
--- Free memory at end of example.c
--- Remove MAX #define in trees.c (conflicted with some libraries)
--- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
--- Declare malloc() and free() in gzio.c if STDC not defined
--- Use malloc() instead of calloc() in zutil.c if int big enough
--- Define STDC for AIX
--- Add aix/ with approach for compiling shared library on AIX
--- Add HP-UX support for shared libraries in configure
--- Add OpenUNIX support for shared libraries in configure
--- Use $cc instead of gcc to build shared library
--- Make prefix directory if needed when installing
--- Correct Macintosh avoidance of typedef Byte in zconf.h
--- Correct Turbo C memory allocation when under Linux
--- Use libz.a instead of -lz in Makefile (assure use of compiled library)
--- Update configure to check for snprintf or vsnprintf functions and their
--  return value, warn during make if using an insecure function
--- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
--  is lost when library is used--resolution is to build new zconf.h
--- Documentation improvements (in zlib.h):
--    - Document raw deflate and inflate
--    - Update RFCs URL
--    - Point out that zlib and gzip formats are different
--    - Note that Z_BUF_ERROR is not fatal
--    - Document string limit for gzprintf() and possible buffer overflow
--    - Note requirement on avail_out when flushing
--    - Note permitted values of flush parameter of inflate()
--- Add some FAQs (and even answers) to the FAQ
--- Add contrib/inflate86/ for x86 faster inflate
--- Add contrib/blast/ for PKWare Data Compression Library decompression
--- Add contrib/puff/ simple inflate for deflate format description
--
--Changes in 1.1.4 (11 March 2002)
--- ZFREE was repeated on same allocation on some error conditions.
--  This creates a security problem described in
--  http://www.zlib.org/advisory-2002-03-11.txt
--- Returned incorrect error (Z_MEM_ERROR) on some invalid data
--- Avoid accesses before window for invalid distances with inflate window
--  less than 32K.
--- force windowBits > 8 to avoid a bug in the encoder for a window size
--  of 256 bytes. (A complete fix will be available in 1.1.5).
--
--Changes in 1.1.3 (9 July 1998)
--- fix "an inflate input buffer bug that shows up on rare but persistent
--  occasions" (Mark)
--- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
--- fix gzseek(..., SEEK_SET) in write mode
--- fix crc check after a gzeek (Frank Faubert)
--- fix miniunzip when the last entry in a zip file is itself a zip file
--  (J Lillge)
--- add contrib/asm586 and contrib/asm686 (Brian Raiter)
--  See http://www.muppetlabs.com/~breadbox/software/assembly.html
--- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
--- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
--- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
--- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
--- added a FAQ file
--
--- Support gzdopen on Mac with Metrowerks (Jason Linhart)
--- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
--- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
--- avoid some warnings with Borland C (Tom Tanner)
--- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
--- emulate utime() for WIN32 in contrib/untgz  (Gilles Vollant)
--- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
--- use libdir and includedir in Makefile.in (Tim Mooney)
--- support shared libraries on OSF1 V4 (Tim Mooney)
--- remove so_locations in "make clean"  (Tim Mooney)
--- fix maketree.c compilation error (Glenn, Mark)
--- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
--- new Makefile.riscos (Rich Walker)
--- initialize static descriptors in trees.c for embedded targets (Nick Smith)
--- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
--- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
--- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
--- fix maketree.c to allow clean compilation of inffixed.h (Mark)
--- fix parameter check in deflateCopy (Gunther Nikl)
--- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
--- Many portability patches by Christian Spieler:
--  . zutil.c, zutil.h: added "const" for zmem*
--  . Make_vms.com: fixed some typos
--  . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
--  . msdos/Makefile.msc: remove "default rtl link library" info from obj files
--  . msdos/Makefile.*: use model-dependent name for the built zlib library
--  . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
--     new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
--- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
--- replace __far with _far for better portability (Christian Spieler, Tom Lane)
--- fix test for errno.h in configure (Tim Newsham)
--
--Changes in 1.1.2 (19 March 98)
--- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
--  See http://www.winimage.com/zLibDll/unzip.html
--- preinitialize the inflate tables for fixed codes, to make the code
--  completely thread safe (Mark)
--- some simplifications and slight speed-up to the inflate code (Mark)
--- fix gzeof on non-compressed files (Allan Schrum)
--- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
--- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
--- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
--- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
--- do not wrap extern "C" around system includes (Tom Lane)
--- mention zlib binding for TCL in README (Andreas Kupries)
--- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
--- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
--- allow "configure --prefix $HOME" (Tim Mooney)
--- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
--- move Makefile.sas to amiga/Makefile.sas
--
--Changes in 1.1.1 (27 Feb 98)
--- fix macros _tr_tally_* in deflate.h for debug mode  (Glenn Randers-Pehrson)
--- remove block truncation heuristic which had very marginal effect for zlib
--  (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
--  compression ratio on some files. This also allows inlining _tr_tally for
--  matches in deflate_slow.
--- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
--
--Changes in 1.1.0 (24 Feb 98)
--- do not return STREAM_END prematurely in inflate (John Bowler)
--- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
--- compile with -DFASTEST to get compression code optimized for speed only
--- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
--- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
--  on Sun but significant on HP)
--
--- add a pointer to experimental unzip library in README (Gilles Vollant)
--- initialize variable gcc in configure (Chris Herborth)
--
--Changes in 1.0.9 (17 Feb 1998)
--- added gzputs and gzgets functions
--- do not clear eof flag in gzseek (Mark Diekhans)
--- fix gzseek for files in transparent mode (Mark Diekhans)
--- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
--- replace EXPORT with ZEXPORT to avoid conflict with other programs
--- added compress2 in zconf.h, zlib.def, zlib.dnt
--- new asm code from Gilles Vollant in contrib/asm386
--- simplify the inflate code (Mark):
-- . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
-- . ZALLOC the length list in inflate_trees_fixed() instead of using stack
-- . ZALLOC the value area for huft_build() instead of using stack
-- . Simplify Z_FINISH check in inflate()
--
--- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
--- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
--- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
--  the declaration of FAR (Gilles VOllant)
--- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
--- read_buf buf parameter of type Bytef* instead of charf*
--- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
--- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
--- fix check for presence of directories in "make install" (Ian Willis)
--
--Changes in 1.0.8 (27 Jan 1998)
--- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
--- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
--- added compress2() to allow setting the compression level
--- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
--- use constant arrays for the static trees in trees.c instead of computing
--  them at run time (thanks to Ken Raeburn for this suggestion). To create
--  trees.h, compile with GEN_TREES_H and run "make test".
--- check return code of example in "make test" and display result
--- pass minigzip command line options to file_compress
--- simplifying code of inflateSync to avoid gcc 2.8 bug
--
--- support CC="gcc -Wall" in configure -s (QingLong)
--- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
--- fix test for shared library support to avoid compiler warnings
--- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
--- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
--- do not use fdopen for Metrowerks on Mac (Brad Pettit))
--- add checks for gzputc and gzputc in example.c
--- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
--- use const for the CRC table (Ken Raeburn)
--- fixed "make uninstall" for shared libraries
--- use Tracev instead of Trace in infblock.c
--- in example.c use correct compressed length for test_sync
--- suppress +vnocompatwarnings in configure for HPUX (not always supported)
--
--Changes in 1.0.7 (20 Jan 1998)
--- fix gzseek which was broken in write mode
--- return error for gzseek to negative absolute position
--- fix configure for Linux (Chun-Chung Chen)
--- increase stack space for MSC (Tim Wegner)
--- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
--- define EXPORTVA for gzprintf (Gilles Vollant)
--- added man page zlib.3 (Rick Rodgers)
--- for contrib/untgz, fix makedir() and improve Makefile
--
--- check gzseek in write mode in example.c
--- allocate extra buffer for seeks only if gzseek is actually called
--- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
--- add inflateSyncPoint in zconf.h
--- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
--
--Changes in 1.0.6 (19 Jan 1998)
--- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
--  gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
--- Fix a deflate bug occurring only with compression level 0 (thanks to
--  Andy Buckler for finding this one).
--- In minigzip, pass transparently also the first byte for .Z files.
--- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
--- check Z_FINISH in inflate (thanks to Marc Schluper)
--- Implement deflateCopy (thanks to Adam Costello)
--- make static libraries by default in configure, add --shared option.
--- move MSDOS or Windows specific files to directory msdos
--- suppress the notion of partial flush to simplify the interface
--  (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
--- suppress history buffer provided by application to simplify the interface
--  (this feature was not implemented anyway in 1.0.4)
--- next_in and avail_in must be initialized before calling inflateInit or
--  inflateInit2
--- add EXPORT in all exported functions (for Windows DLL)
--- added Makefile.nt (thanks to Stephen Williams)
--- added the unsupported "contrib" directory:
--   contrib/asm386/ by Gilles Vollant <info@winimage.com>
--        386 asm code replacing longest_match().
--   contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
--        A C++ I/O streams interface to the zlib gz* functions
--   contrib/iostream2/  by Tyge Løvset <Tyge.Lovset@cmr.no>
--        Another C++ I/O streams interface
--   contrib/untgz/  by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
--        A very simple tar.gz file extractor using zlib
--   contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
--        How to use compress(), uncompress() and the gz* functions from VB.
--- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
--  level) in minigzip (thanks to Tom Lane)
--
--- use const for rommable constants in deflate
--- added test for gzseek and gztell in example.c
--- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
--- add undocumented function zError to convert error code to string
--  (for Tim Smithers)
--- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
--- Use default memcpy for Symantec MSDOS compiler.
--- Add EXPORT keyword for check_func (needed for Windows DLL)
--- add current directory to LD_LIBRARY_PATH for "make test"
--- create also a link for libz.so.1
--- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
--- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
--- added -soname for Linux in configure (Chun-Chung Chen,
--- assign numbers to the exported functions in zlib.def (for Windows DLL)
--- add advice in zlib.h for best usage of deflateSetDictionary
--- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
--- allow compilation with ANSI keywords only enabled for TurboC in large model
--- avoid "versionString"[0] (Borland bug)
--- add NEED_DUMMY_RETURN for Borland
--- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
--- allow compilation with CC
--- defined STDC for OS/2 (David Charlap)
--- limit external names to 8 chars for MVS (Thomas Lund)
--- in minigzip.c, use static buffers only for 16-bit systems
--- fix suffix check for "minigzip -d foo.gz"
--- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
--- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
--- added makelcc.bat for lcc-win32 (Tom St Denis)
--- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
--- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
--- check for unistd.h in configure (for off_t)
--- remove useless check parameter in inflate_blocks_free
--- avoid useless assignment of s->check to itself in inflate_blocks_new
--- do not flush twice in gzclose (thanks to Ken Raeburn)
--- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
--- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
--- work around buggy fclose on pipes for HP/UX
--- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
--- fix configure if CC is already equal to gcc
--
--Changes in 1.0.5 (3 Jan 98)
--- Fix inflate to terminate gracefully when fed corrupted or invalid data
--- Use const for rommable constants in inflate
--- Eliminate memory leaks on error conditions in inflate
--- Removed some vestigial code in inflate
--- Update web address in README
--
--Changes in 1.0.4 (24 Jul 96)
--- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
--  bit, so the decompressor could decompress all the correct data but went
--  on to attempt decompressing extra garbage data. This affected minigzip too.
--- zlibVersion and gzerror return const char* (needed for DLL)
--- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
--- use z_error only for DEBUG (avoid problem with DLLs)
--
--Changes in 1.0.3 (2 Jul 96)
--- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
--  small and medium models; this makes the library incompatible with previous
--  versions for these models. (No effect in large model or on other systems.)
--- return OK instead of BUF_ERROR if previous deflate call returned with
--  avail_out as zero but there is nothing to do
--- added memcmp for non STDC compilers
--- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
--- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
--- better check for 16-bit mode MSC (avoids problem with Symantec)
--
--Changes in 1.0.2 (23 May 96)
--- added Windows DLL support
--- added a function zlibVersion (for the DLL support)
--- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
--- Bytef is define's instead of typedef'd only for Borland C
--- avoid reading uninitialized memory in example.c
--- mention in README that the zlib format is now RFC1950
--- updated Makefile.dj2
--- added algorithm.doc
--
--Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
--- fix array overlay in deflate.c which sometimes caused bad compressed data
--- fix inflate bug with empty stored block
--- fix MSDOS medium model which was broken in 0.99
--- fix deflateParams() which could generate bad compressed data.
--- Bytef is define'd instead of typedef'ed (work around Borland bug)
--- added an INDEX file
--- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
--  Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
--- speed up adler32 for modern machines without auto-increment
--- added -ansi for IRIX in configure
--- static_init_done in trees.c is an int
--- define unlink as delete for VMS
--- fix configure for QNX
--- add configure branch for SCO and HPUX
--- avoid many warnings (unused variables, dead assignments, etc...)
--- no fdopen for BeOS
--- fix the Watcom fix for 32 bit mode (define FAR as empty)
--- removed redefinition of Byte for MKWERKS
--- work around an MWKERKS bug (incorrect merge of all .h files)
--
--Changes in 0.99 (27 Jan 96)
--- allow preset dictionary shared between compressor and decompressor
--- allow compression level 0 (no compression)
--- add deflateParams in zlib.h: allow dynamic change of compression level
--  and compression strategy.
--- test large buffers and deflateParams in example.c
--- add optional "configure" to build zlib as a shared library
--- suppress Makefile.qnx, use configure instead
--- fixed deflate for 64-bit systems (detected on Cray)
--- fixed inflate_blocks for 64-bit systems (detected on Alpha)
--- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
--- always return Z_BUF_ERROR when deflate() has nothing to do
--- deflateInit and inflateInit are now macros to allow version checking
--- prefix all global functions and types with z_ with -DZ_PREFIX
--- make falloc completely reentrant (inftrees.c)
--- fixed very unlikely race condition in ct_static_init
--- free in reverse order of allocation to help memory manager
--- use zlib-1.0/* instead of zlib/* inside the tar.gz
--- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
--  -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
--- allow gzread on concatenated .gz files
--- deflateEnd now returns Z_DATA_ERROR if it was premature
--- deflate is finally (?) fully deterministic (no matches beyond end of input)
--- Document Z_SYNC_FLUSH
--- add uninstall in Makefile
--- Check for __cpluplus in zlib.h
--- Better test in ct_align for partial flush
--- avoid harmless warnings for Borland C++
--- initialize hash_head in deflate.c
--- avoid warning on fdopen (gzio.c) for HP cc -Aa
--- include stdlib.h for STDC compilers
--- include errno.h for Cray
--- ignore error if ranlib doesn't exist
--- call ranlib twice for NeXTSTEP
--- use exec_prefix instead of prefix for libz.a
--- renamed ct_* as _tr_* to avoid conflict with applications
--- clear z->msg in inflateInit2 before any error return
--- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
--- fixed typo in zconf.h (_GNUC__ => __GNUC__)
--- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
--- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
--- in fcalloc, normalize pointer if size > 65520 bytes
--- don't use special fcalloc for 32 bit Borland C++
--- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
--- use Z_BINARY instead of BINARY
--- document that gzclose after gzdopen will close the file
--- allow "a" as mode in gzopen.
--- fix error checking in gzread
--- allow skipping .gz extra-field on pipes
--- added reference to Perl interface in README
--- put the crc table in FAR data (I dislike more and more the medium model :)
--- added get_crc_table
--- added a dimension to all arrays (Borland C can't count).
--- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
--- guard against multiple inclusion of *.h (for precompiled header on Mac)
--- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
--- don't use unsized arrays to avoid silly warnings by Visual C++:
--     warning C4746: 'inflate_mask' : unsized array treated as  '__far'
--     (what's wrong with far data in far model?).
--- define enum out of inflate_blocks_state to allow compilation with C++
--
--Changes in 0.95 (16 Aug 95)
--- fix MSDOS small and medium model (now easier to adapt to any compiler)
--- inlined send_bits
--- fix the final (:-) bug for deflate with flush (output was correct but
--  not completely flushed in rare occasions).
--- default window size is same for compression and decompression
--  (it's now sufficient to set MAX_WBITS in zconf.h).
--- voidp -> voidpf and voidnp -> voidp (for consistency with other
--  typedefs and because voidnp was not near in large model).
--
--Changes in 0.94 (13 Aug 95)
--- support MSDOS medium model
--- fix deflate with flush (could sometimes generate bad output)
--- fix deflateReset (zlib header was incorrectly suppressed)
--- added support for VMS
--- allow a compression level in gzopen()
--- gzflush now calls fflush
--- For deflate with flush, flush even if no more input is provided.
--- rename libgz.a as libz.a
--- avoid complex expression in infcodes.c triggering Turbo C bug
--- work around a problem with gcc on Alpha (in INSERT_STRING)
--- don't use inline functions (problem with some gcc versions)
--- allow renaming of Byte, uInt, etc... with #define.
--- avoid warning about (unused) pointer before start of array in deflate.c
--- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
--- avoid reserved word 'new' in trees.c
--
--Changes in 0.93 (25 June 95)
--- temporarily disable inline functions
--- make deflate deterministic
--- give enough lookahead for PARTIAL_FLUSH
--- Set binary mode for stdin/stdout in minigzip.c for OS/2
--- don't even use signed char in inflate (not portable enough)
--- fix inflate memory leak for segmented architectures
--
--Changes in 0.92 (3 May 95)
--- don't assume that char is signed (problem on SGI)
--- Clear bit buffer when starting a stored block
--- no memcpy on Pyramid
--- suppressed inftest.c
--- optimized fill_window, put longest_match inline for gcc
--- optimized inflate on stored blocks.
--- untabify all sources to simplify patches
--
--Changes in 0.91 (2 May 95)
--- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
--- Document the memory requirements in zconf.h
--- added "make install"
--- fix sync search logic in inflateSync
--- deflate(Z_FULL_FLUSH) now works even if output buffer too short
--- after inflateSync, don't scare people with just "lo world"
--- added support for DJGPP
--
--Changes in 0.9 (1 May 95)
--- don't assume that zalloc clears the allocated memory (the TurboC bug
--  was Mark's bug after all :)
--- let again gzread copy uncompressed data unchanged (was working in 0.71)
--- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
--- added a test of inflateSync in example.c
--- moved MAX_WBITS to zconf.h because users might want to change that.
--- document explicitly that zalloc(64K) on MSDOS must return a normalized
--  pointer (zero offset)
--- added Makefiles for Microsoft C, Turbo C, Borland C++
--- faster crc32()
--
--Changes in 0.8 (29 April 95)
--- added fast inflate (inffast.c)
--- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
--  is incompatible with previous versions of zlib which returned Z_OK.
--- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
--  (actually that was not a compiler bug, see 0.81 above)
--- gzread no longer reads one extra byte in certain cases
--- In gzio destroy(), don't reference a freed structure
--- avoid many warnings for MSDOS
--- avoid the ERROR symbol which is used by MS Windows
--
--Changes in 0.71 (14 April 95)
--- Fixed more MSDOS compilation problems :( There is still a bug with
--  TurboC large model.
--
--Changes in 0.7 (14 April 95)
--- Added full inflate support.
--- Simplified the crc32() interface. The pre- and post-conditioning
--  (one's complement) is now done inside crc32(). WARNING: this is
--  incompatible with previous versions; see zlib.h for the new usage.
--
--Changes in 0.61 (12 April 95)
--- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
--
--Changes in 0.6 (11 April 95)
--- added minigzip.c
--- added gzdopen to reopen a file descriptor as gzFile
--- added transparent reading of non-gziped files in gzread.
--- fixed bug in gzread (don't read crc as data)
--- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
--- don't allocate big arrays in the stack (for MSDOS)
--- fix some MSDOS compilation problems
--
--Changes in 0.5:
--- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
--  not yet Z_FULL_FLUSH.
--- support decompression but only in a single step (forced Z_FINISH)
--- added opaque object for zalloc and zfree.
--- added deflateReset and inflateReset
--- added a variable zlib_version for consistency checking.
--- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
--  Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
--
--Changes in 0.4:
--- avoid "zip" everywhere, use zlib instead of ziplib.
--- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
--  if compression method == 8.
--- added adler32 and crc32
--- renamed deflateOptions as deflateInit2, call one or the other but not both
--- added the method parameter for deflateInit2.
--- added inflateInit2
--- simplied considerably deflateInit and inflateInit by not supporting
--  user-provided history buffer. This is supported only in deflateInit2
--  and inflateInit2.
--
--Changes in 0.3:
--- prefix all macro names with Z_
--- use Z_FINISH instead of deflateEnd to finish compression.
--- added Z_HUFFMAN_ONLY
--- added gzerror()
diff --cc zlib/FAQ
index 99b7cf92e45497fc8f608777f962dce2148d108b,99b7cf92e45497fc8f608777f962dce2148d108b..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,368 -1,368 +1,0 @@@
--
--                Frequently Asked Questions about zlib
--
--
--If your question is not there, please check the zlib home page
--http://zlib.net/ which may have more recent information.
--The lastest zlib FAQ is at http://zlib.net/zlib_faq.html
--
--
-- 1. Is zlib Y2K-compliant?
--
--    Yes. zlib doesn't handle dates.
--
-- 2. Where can I get a Windows DLL version?
--
--    The zlib sources can be compiled without change to produce a DLL.  See the
--    file win32/DLL_FAQ.txt in the zlib distribution.  Pointers to the
--    precompiled DLL are found in the zlib web site at http://zlib.net/ .
--
-- 3. Where can I get a Visual Basic interface to zlib?
--
--    See
--        * http://marknelson.us/1997/01/01/zlib-engine/
--        * win32/DLL_FAQ.txt in the zlib distribution
--
-- 4. compress() returns Z_BUF_ERROR.
--
--    Make sure that before the call of compress(), the length of the compressed
--    buffer is equal to the available size of the compressed buffer and not
--    zero.  For Visual Basic, check that this parameter is passed by reference
--    ("as any"), not by value ("as long").
--
-- 5. deflate() or inflate() returns Z_BUF_ERROR.
--
--    Before making the call, make sure that avail_in and avail_out are not zero.
--    When setting the parameter flush equal to Z_FINISH, also make sure that
--    avail_out is big enough to allow processing all pending input.  Note that a
--    Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be
--    made with more input or output space.  A Z_BUF_ERROR may in fact be
--    unavoidable depending on how the functions are used, since it is not
--    possible to tell whether or not there is more output pending when
--    strm.avail_out returns with zero.  See http://zlib.net/zlib_how.html for a
--    heavily annotated example.
--
-- 6. Where's the zlib documentation (man pages, etc.)?
--
--    It's in zlib.h .  Examples of zlib usage are in the files test/example.c
--    and test/minigzip.c, with more in examples/ .
--
-- 7. Why don't you use GNU autoconf or libtool or ...?
--
--    Because we would like to keep zlib as a very small and simple package.
--    zlib is rather portable and doesn't need much configuration.
--
-- 8. I found a bug in zlib.
--
--    Most of the time, such problems are due to an incorrect usage of zlib.
--    Please try to reproduce the problem with a small program and send the
--    corresponding source to us at zlib@gzip.org .  Do not send multi-megabyte
--    data files without prior agreement.
--
-- 9. Why do I get "undefined reference to gzputc"?
--
--    If "make test" produces something like
--
--       example.o(.text+0x154): undefined reference to `gzputc'
--
--    check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
--    /usr/X11R6/lib. Remove any old versions, then do "make install".
--
--10. I need a Delphi interface to zlib.
--
--    See the contrib/delphi directory in the zlib distribution.
--
--11. Can zlib handle .zip archives?
--
--    Not by itself, no.  See the directory contrib/minizip in the zlib
--    distribution.
--
--12. Can zlib handle .Z files?
--
--    No, sorry.  You have to spawn an uncompress or gunzip subprocess, or adapt
--    the code of uncompress on your own.
--
--13. How can I make a Unix shared library?
--
--    By default a shared (and a static) library is built for Unix.  So:
--
--    make distclean
--    ./configure
--    make
--
--14. How do I install a shared zlib library on Unix?
--
--    After the above, then:
--
--    make install
--
--    However, many flavors of Unix come with a shared zlib already installed.
--    Before going to the trouble of compiling a shared version of zlib and
--    trying to install it, you may want to check if it's already there!  If you
--    can #include <zlib.h>, it's there.  The -lz option will probably link to
--    it.  You can check the version at the top of zlib.h or with the
--    ZLIB_VERSION symbol defined in zlib.h .
--
--15. I have a question about OttoPDF.
--
--    We are not the authors of OttoPDF. The real author is on the OttoPDF web
--    site: Joel Hainley, jhainley@myndkryme.com.
--
--16. Can zlib decode Flate data in an Adobe PDF file?
--
--    Yes. See http://www.pdflib.com/ . To modify PDF forms, see
--    http://sourceforge.net/projects/acroformtool/ .
--
--17. Why am I getting this "register_frame_info not found" error on Solaris?
--
--    After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
--    generates an error such as:
--
--        ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
--        symbol __register_frame_info: referenced symbol not found
--
--    The symbol __register_frame_info is not part of zlib, it is generated by
--    the C compiler (cc or gcc).  You must recompile applications using zlib
--    which have this problem.  This problem is specific to Solaris.  See
--    http://www.sunfreeware.com for Solaris versions of zlib and applications
--    using zlib.
--
--18. Why does gzip give an error on a file I make with compress/deflate?
--
--    The compress and deflate functions produce data in the zlib format, which
--    is different and incompatible with the gzip format.  The gz* functions in
--    zlib on the other hand use the gzip format.  Both the zlib and gzip formats
--    use the same compressed data format internally, but have different headers
--    and trailers around the compressed data.
--
--19. Ok, so why are there two different formats?
--
--    The gzip format was designed to retain the directory information about a
--    single file, such as the name and last modification date.  The zlib format
--    on the other hand was designed for in-memory and communication channel
--    applications, and has a much more compact header and trailer and uses a
--    faster integrity check than gzip.
--
--20. Well that's nice, but how do I make a gzip file in memory?
--
--    You can request that deflate write the gzip format instead of the zlib
--    format using deflateInit2().  You can also request that inflate decode the
--    gzip format using inflateInit2().  Read zlib.h for more details.
--
--21. Is zlib thread-safe?
--
--    Yes.  However any library routines that zlib uses and any application-
--    provided memory allocation routines must also be thread-safe.  zlib's gz*
--    functions use stdio library routines, and most of zlib's functions use the
--    library memory allocation routines by default.  zlib's *Init* functions
--    allow for the application to provide custom memory allocation routines.
--
--    Of course, you should only operate on any given zlib or gzip stream from a
--    single thread at a time.
--
--22. Can I use zlib in my commercial application?
--
--    Yes.  Please read the license in zlib.h.
--
--23. Is zlib under the GNU license?
--
--    No.  Please read the license in zlib.h.
--
--24. The license says that altered source versions must be "plainly marked". So
--    what exactly do I need to do to meet that requirement?
--
--    You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h.  In
--    particular, the final version number needs to be changed to "f", and an
--    identification string should be appended to ZLIB_VERSION.  Version numbers
--    x.x.x.f are reserved for modifications to zlib by others than the zlib
--    maintainers.  For example, if the version of the base zlib you are altering
--    is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
--    ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3".  You can also
--    update the version strings in deflate.c and inftrees.c.
--
--    For altered source distributions, you should also note the origin and
--    nature of the changes in zlib.h, as well as in ChangeLog and README, along
--    with the dates of the alterations.  The origin should include at least your
--    name (or your company's name), and an email address to contact for help or
--    issues with the library.
--
--    Note that distributing a compiled zlib library along with zlib.h and
--    zconf.h is also a source distribution, and so you should change
--    ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
--    in zlib.h as you would for a full source distribution.
--
--25. Will zlib work on a big-endian or little-endian architecture, and can I
--    exchange compressed data between them?
--
--    Yes and yes.
--
--26. Will zlib work on a 64-bit machine?
--
--    Yes.  It has been tested on 64-bit machines, and has no dependence on any
--    data types being limited to 32-bits in length.  If you have any
--    difficulties, please provide a complete problem report to zlib@gzip.org
--
--27. Will zlib decompress data from the PKWare Data Compression Library?
--
--    No.  The PKWare DCL uses a completely different compressed data format than
--    does PKZIP and zlib.  However, you can look in zlib's contrib/blast
--    directory for a possible solution to your problem.
--
--28. Can I access data randomly in a compressed stream?
--
--    No, not without some preparation.  If when compressing you periodically use
--    Z_FULL_FLUSH, carefully write all the pending data at those points, and
--    keep an index of those locations, then you can start decompression at those
--    points.  You have to be careful to not use Z_FULL_FLUSH too often, since it
--    can significantly degrade compression.  Alternatively, you can scan a
--    deflate stream once to generate an index, and then use that index for
--    random access.  See examples/zran.c .
--
--29. Does zlib work on MVS, OS/390, CICS, etc.?
--
--    It has in the past, but we have not heard of any recent evidence.  There
--    were working ports of zlib 1.1.4 to MVS, but those links no longer work.
--    If you know of recent, successful applications of zlib on these operating
--    systems, please let us know.  Thanks.
--
--30. Is there some simpler, easier to read version of inflate I can look at to
--    understand the deflate format?
--
--    First off, you should read RFC 1951.  Second, yes.  Look in zlib's
--    contrib/puff directory.
--
--31. Does zlib infringe on any patents?
--
--    As far as we know, no.  In fact, that was originally the whole point behind
--    zlib.  Look here for some more information:
--
--    http://www.gzip.org/#faq11
--
--32. Can zlib work with greater than 4 GB of data?
--
--    Yes.  inflate() and deflate() will process any amount of data correctly.
--    Each call of inflate() or deflate() is limited to input and output chunks
--    of the maximum value that can be stored in the compiler's "unsigned int"
--    type, but there is no limit to the number of chunks.  Note however that the
--    strm.total_in and strm_total_out counters may be limited to 4 GB.  These
--    counters are provided as a convenience and are not used internally by
--    inflate() or deflate().  The application can easily set up its own counters
--    updated after each call of inflate() or deflate() to count beyond 4 GB.
--    compress() and uncompress() may be limited to 4 GB, since they operate in a
--    single call.  gzseek() and gztell() may be limited to 4 GB depending on how
--    zlib is compiled.  See the zlibCompileFlags() function in zlib.h.
--
--    The word "may" appears several times above since there is a 4 GB limit only
--    if the compiler's "long" type is 32 bits.  If the compiler's "long" type is
--    64 bits, then the limit is 16 exabytes.
--
--33. Does zlib have any security vulnerabilities?
--
--    The only one that we are aware of is potentially in gzprintf().  If zlib is
--    compiled to use sprintf() or vsprintf(), then there is no protection
--    against a buffer overflow of an 8K string space (or other value as set by
--    gzbuffer()), other than the caller of gzprintf() assuring that the output
--    will not exceed 8K.  On the other hand, if zlib is compiled to use
--    snprintf() or vsnprintf(), which should normally be the case, then there is
--    no vulnerability.  The ./configure script will display warnings if an
--    insecure variation of sprintf() will be used by gzprintf().  Also the
--    zlibCompileFlags() function will return information on what variant of
--    sprintf() is used by gzprintf().
--
--    If you don't have snprintf() or vsnprintf() and would like one, you can
--    find a portable implementation here:
--
--        http://www.ijs.si/software/snprintf/
--
--    Note that you should be using the most recent version of zlib.  Versions
--    1.1.3 and before were subject to a double-free vulnerability, and versions
--    1.2.1 and 1.2.2 were subject to an access exception when decompressing
--    invalid compressed data.
--
--34. Is there a Java version of zlib?
--
--    Probably what you want is to use zlib in Java. zlib is already included
--    as part of the Java SDK in the java.util.zip package. If you really want
--    a version of zlib written in the Java language, look on the zlib home
--    page for links: http://zlib.net/ .
--
--35. I get this or that compiler or source-code scanner warning when I crank it
--    up to maximally-pedantic. Can't you guys write proper code?
--
--    Many years ago, we gave up attempting to avoid warnings on every compiler
--    in the universe.  It just got to be a waste of time, and some compilers
--    were downright silly as well as contradicted each other.  So now, we simply
--    make sure that the code always works.
--
--36. Valgrind (or some similar memory access checker) says that deflate is
--    performing a conditional jump that depends on an uninitialized value.
--    Isn't that a bug?
--
--    No.  That is intentional for performance reasons, and the output of deflate
--    is not affected.  This only started showing up recently since zlib 1.2.x
--    uses malloc() by default for allocations, whereas earlier versions used
--    calloc(), which zeros out the allocated memory.  Even though the code was
--    correct, versions 1.2.4 and later was changed to not stimulate these
--    checkers.
--
--37. Will zlib read the (insert any ancient or arcane format here) compressed
--    data format?
--
--    Probably not. Look in the comp.compression FAQ for pointers to various
--    formats and associated software.
--
--38. How can I encrypt/decrypt zip files with zlib?
--
--    zlib doesn't support encryption.  The original PKZIP encryption is very
--    weak and can be broken with freely available programs.  To get strong
--    encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib
--    compression.  For PKZIP compatible "encryption", look at
--    http://www.info-zip.org/
--
--39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
--
--    "gzip" is the gzip format, and "deflate" is the zlib format.  They should
--    probably have called the second one "zlib" instead to avoid confusion with
--    the raw deflate compressed data format.  While the HTTP 1.1 RFC 2616
--    correctly points to the zlib specification in RFC 1950 for the "deflate"
--    transfer encoding, there have been reports of servers and browsers that
--    incorrectly produce or expect raw deflate data per the deflate
--    specification in RFC 1951, most notably Microsoft.  So even though the
--    "deflate" transfer encoding using the zlib format would be the more
--    efficient approach (and in fact exactly what the zlib format was designed
--    for), using the "gzip" transfer encoding is probably more reliable due to
--    an unfortunate choice of name on the part of the HTTP 1.1 authors.
--
--    Bottom line: use the gzip format for HTTP 1.1 encoding.
--
--40. Does zlib support the new "Deflate64" format introduced by PKWare?
--
--    No.  PKWare has apparently decided to keep that format proprietary, since
--    they have not documented it as they have previous compression formats.  In
--    any case, the compression improvements are so modest compared to other more
--    modern approaches, that it's not worth the effort to implement.
--
--41. I'm having a problem with the zip functions in zlib, can you help?
--
--    There are no zip functions in zlib.  You are probably using minizip by
--    Giles Vollant, which is found in the contrib directory of zlib.  It is not
--    part of zlib.  In fact none of the stuff in contrib is part of zlib.  The
--    files in there are not supported by the zlib authors.  You need to contact
--    the authors of the respective contribution for help.
--
--42. The match.asm code in contrib is under the GNU General Public License.
--    Since it's part of zlib, doesn't that mean that all of zlib falls under the
--    GNU GPL?
--
--    No.  The files in contrib are not part of zlib.  They were contributed by
--    other authors and are provided as a convenience to the user within the zlib
--    distribution.  Each item in contrib has its own license.
--
--43. Is zlib subject to export controls?  What is its ECCN?
--
--    zlib is not subject to export controls, and so is classified as EAR99.
--
--44. Can you please sign these lengthy legal documents and fax them back to us
--    so that we can use your software in our product?
--
--    No. Go away. Shoo.
diff --cc zlib/Makefile.in.zlib
index 5a77949ff068571e915b8e69e2012b9b31ad39dd,5a77949ff068571e915b8e69e2012b9b31ad39dd..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,410 -1,410 +1,0 @@@
--# Makefile for zlib
--# Copyright (C) 1995-2017 Jean-loup Gailly, Mark Adler
--# For conditions of distribution and use, see copyright notice in zlib.h
--
--# To compile and test, type:
--#    ./configure; make test
--# Normally configure builds both a static and a shared library.
--# If you want to build just a static library, use: ./configure --static
--
--# To use the asm code, type:
--#    cp contrib/asm?86/match.S ./match.S
--#    make LOC=-DASMV OBJA=match.o
--
--# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
--#    make install
--# To install in $HOME instead of /usr/local, use:
--#    make install prefix=$HOME
--
--CC=cc
--
--CFLAGS=-O
--#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
--#CFLAGS=-g -DZLIB_DEBUG
--#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
--#           -Wstrict-prototypes -Wmissing-prototypes
--
--SFLAGS=-O
--LDFLAGS=
--TEST_LDFLAGS=-L. libz.a
--LDSHARED=$(CC)
--CPP=$(CC) -E
--
--STATICLIB=libz.a
--SHAREDLIB=libz.so
--SHAREDLIBV=libz.so.1.2.11
--SHAREDLIBM=libz.so.1
--LIBS=$(STATICLIB) $(SHAREDLIBV)
--
--AR=ar
--ARFLAGS=rc
--RANLIB=ranlib
--LDCONFIG=ldconfig
--LDSHAREDLIBC=-lc
--TAR=tar
--SHELL=/bin/sh
--EXE=
--
--prefix = /usr/local
--exec_prefix = ${prefix}
--libdir = ${exec_prefix}/lib
--sharedlibdir = ${libdir}
--includedir = ${prefix}/include
--mandir = ${prefix}/share/man
--man3dir = ${mandir}/man3
--pkgconfigdir = ${libdir}/pkgconfig
--SRCDIR=
--ZINC=
--ZINCOUT=-I.
--
--OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o
--OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o
--OBJC = $(OBJZ) $(OBJG)
--
--PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo
--PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo
--PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG)
--
--# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo
--OBJA =
--PIC_OBJA =
--
--OBJS = $(OBJC) $(OBJA)
--
--PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA)
--
--all: static shared
--
--static: example$(EXE) minigzip$(EXE)
--
--shared: examplesh$(EXE) minigzipsh$(EXE)
--
--all64: example64$(EXE) minigzip64$(EXE)
--
--check: test
--
--test: all teststatic testshared
--
--teststatic: static
--      @TMPST=tmpst_$$; \
--      if echo hello world | ./minigzip | ./minigzip -d && ./example $$TMPST ; then \
--        echo '                *** zlib test OK ***'; \
--      else \
--        echo '                *** zlib test FAILED ***'; false; \
--      fi; \
--      rm -f $$TMPST
--
--testshared: shared
--      @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
--      LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \
--      DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \
--      SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \
--      TMPSH=tmpsh_$$; \
--      if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh $$TMPSH; then \
--        echo '                *** zlib shared test OK ***'; \
--      else \
--        echo '                *** zlib shared test FAILED ***'; false; \
--      fi; \
--      rm -f $$TMPSH
--
--test64: all64
--      @TMP64=tmp64_$$; \
--      if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64 $$TMP64; then \
--        echo '                *** zlib 64-bit test OK ***'; \
--      else \
--        echo '                *** zlib 64-bit test FAILED ***'; false; \
--      fi; \
--      rm -f $$TMP64
--
--infcover.o: $(SRCDIR)test/infcover.c $(SRCDIR)zlib.h zconf.h
--      $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/infcover.c
--
--infcover: infcover.o libz.a
--      $(CC) $(CFLAGS) -o $@ infcover.o libz.a
--
--cover: infcover
--      rm -f *.gcda
--      ./infcover
--      gcov inf*.c
--
--libz.a: $(OBJS)
--      $(AR) $(ARFLAGS) $@ $(OBJS)
--      -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
--
--match.o: match.S
--      $(CPP) match.S > _match.s
--      $(CC) -c _match.s
--      mv _match.o match.o
--      rm -f _match.s
--
--match.lo: match.S
--      $(CPP) match.S > _match.s
--      $(CC) -c -fPIC _match.s
--      mv _match.o match.lo
--      rm -f _match.s
--
--example.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h
--      $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/example.c
--
--minigzip.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h
--      $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/minigzip.c
--
--example64.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h
--      $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/example.c
--
--minigzip64.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h
--      $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/minigzip.c
--
--
--adler32.o: $(SRCDIR)adler32.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)adler32.c
--
--crc32.o: $(SRCDIR)crc32.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)crc32.c
--
--deflate.o: $(SRCDIR)deflate.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)deflate.c
--
--infback.o: $(SRCDIR)infback.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)infback.c
--
--inffast.o: $(SRCDIR)inffast.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inffast.c
--
--inflate.o: $(SRCDIR)inflate.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inflate.c
--
--inftrees.o: $(SRCDIR)inftrees.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inftrees.c
--
--trees.o: $(SRCDIR)trees.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)trees.c
--
--zutil.o: $(SRCDIR)zutil.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)zutil.c
--
--compress.o: $(SRCDIR)compress.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)compress.c
--
--uncompr.o: $(SRCDIR)uncompr.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)uncompr.c
--
--gzclose.o: $(SRCDIR)gzclose.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzclose.c
--
--gzlib.o: $(SRCDIR)gzlib.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzlib.c
--
--gzread.o: $(SRCDIR)gzread.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzread.c
--
--gzwrite.o: $(SRCDIR)gzwrite.c
--      $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzwrite.c
--
--
--adler32.lo: $(SRCDIR)adler32.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/adler32.o $(SRCDIR)adler32.c
--      -@mv objs/adler32.o $@
--
--crc32.lo: $(SRCDIR)crc32.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/crc32.o $(SRCDIR)crc32.c
--      -@mv objs/crc32.o $@
--
--deflate.lo: $(SRCDIR)deflate.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/deflate.o $(SRCDIR)deflate.c
--      -@mv objs/deflate.o $@
--
--infback.lo: $(SRCDIR)infback.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/infback.o $(SRCDIR)infback.c
--      -@mv objs/infback.o $@
--
--inffast.lo: $(SRCDIR)inffast.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inffast.o $(SRCDIR)inffast.c
--      -@mv objs/inffast.o $@
--
--inflate.lo: $(SRCDIR)inflate.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inflate.o $(SRCDIR)inflate.c
--      -@mv objs/inflate.o $@
--
--inftrees.lo: $(SRCDIR)inftrees.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inftrees.o $(SRCDIR)inftrees.c
--      -@mv objs/inftrees.o $@
--
--trees.lo: $(SRCDIR)trees.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/trees.o $(SRCDIR)trees.c
--      -@mv objs/trees.o $@
--
--zutil.lo: $(SRCDIR)zutil.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/zutil.o $(SRCDIR)zutil.c
--      -@mv objs/zutil.o $@
--
--compress.lo: $(SRCDIR)compress.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/compress.o $(SRCDIR)compress.c
--      -@mv objs/compress.o $@
--
--uncompr.lo: $(SRCDIR)uncompr.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/uncompr.o $(SRCDIR)uncompr.c
--      -@mv objs/uncompr.o $@
--
--gzclose.lo: $(SRCDIR)gzclose.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzclose.o $(SRCDIR)gzclose.c
--      -@mv objs/gzclose.o $@
--
--gzlib.lo: $(SRCDIR)gzlib.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzlib.o $(SRCDIR)gzlib.c
--      -@mv objs/gzlib.o $@
--
--gzread.lo: $(SRCDIR)gzread.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzread.o $(SRCDIR)gzread.c
--      -@mv objs/gzread.o $@
--
--gzwrite.lo: $(SRCDIR)gzwrite.c
--      -@mkdir objs 2>/dev/null || test -d objs
--      $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzwrite.o $(SRCDIR)gzwrite.c
--      -@mv objs/gzwrite.o $@
--
--
--placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a
--      $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS)
--      rm -f $(SHAREDLIB) $(SHAREDLIBM)
--      ln -s $@ $(SHAREDLIB)
--      ln -s $@ $(SHAREDLIBM)
--      -@rmdir objs
--
--example$(EXE): example.o $(STATICLIB)
--      $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS)
--
--minigzip$(EXE): minigzip.o $(STATICLIB)
--      $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS)
--
--examplesh$(EXE): example.o $(SHAREDLIBV)
--      $(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV)
--
--minigzipsh$(EXE): minigzip.o $(SHAREDLIBV)
--      $(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV)
--
--example64$(EXE): example64.o $(STATICLIB)
--      $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS)
--
--minigzip64$(EXE): minigzip64.o $(STATICLIB)
--      $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS)
--
--install-libs: $(LIBS)
--      -@if [ ! -d $(DESTDIR)$(exec_prefix)  ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
--      -@if [ ! -d $(DESTDIR)$(libdir)       ]; then mkdir -p $(DESTDIR)$(libdir); fi
--      -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi
--      -@if [ ! -d $(DESTDIR)$(man3dir)      ]; then mkdir -p $(DESTDIR)$(man3dir); fi
--      -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
--      rm -f $(DESTDIR)$(libdir)/$(STATICLIB)
--      cp $(STATICLIB) $(DESTDIR)$(libdir)
--      chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB)
--      -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1
--      -@if test -n "$(SHAREDLIBV)"; then \
--        rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \
--        cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \
--        echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \
--        chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \
--        echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \
--        rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
--        ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \
--        ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
--        ($(LDCONFIG) || true)  >/dev/null 2>&1; \
--      fi
--      rm -f $(DESTDIR)$(man3dir)/zlib.3
--      cp $(SRCDIR)zlib.3 $(DESTDIR)$(man3dir)
--      chmod 644 $(DESTDIR)$(man3dir)/zlib.3
--      rm -f $(DESTDIR)$(pkgconfigdir)/zlib.pc
--      cp zlib.pc $(DESTDIR)$(pkgconfigdir)
--      chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc
--# The ranlib in install is needed on NeXTSTEP which checks file times
--# ldconfig is for Linux
--
--install: install-libs
--      -@if [ ! -d $(DESTDIR)$(includedir)   ]; then mkdir -p $(DESTDIR)$(includedir); fi
--      rm -f $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
--      cp $(SRCDIR)zlib.h zconf.h $(DESTDIR)$(includedir)
--      chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
--
--uninstall:
--      cd $(DESTDIR)$(includedir) && rm -f zlib.h zconf.h
--      cd $(DESTDIR)$(libdir) && rm -f libz.a; \
--      if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \
--        rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
--      fi
--      cd $(DESTDIR)$(man3dir) && rm -f zlib.3
--      cd $(DESTDIR)$(pkgconfigdir) && rm -f zlib.pc
--
--docs: zlib.3.pdf
--
--zlib.3.pdf: $(SRCDIR)zlib.3
--      groff -mandoc -f H -T ps $(SRCDIR)zlib.3 | ps2pdf - $@
--
--zconf.h.cmakein: $(SRCDIR)zconf.h.in
--      -@ TEMPFILE=zconfh_$$; \
--      echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" >> $$TEMPFILE &&\
--      sed -f $$TEMPFILE $(SRCDIR)zconf.h.in > $@ &&\
--      touch -r $(SRCDIR)zconf.h.in $@ &&\
--      rm $$TEMPFILE
--
--zconf: $(SRCDIR)zconf.h.in
--      cp -p $(SRCDIR)zconf.h.in zconf.h
--
--mostlyclean: clean
--clean:
--      rm -f *.o *.lo *~ \
--         example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \
--         example64$(EXE) minigzip64$(EXE) \
--         infcover \
--         libz.* foo.gz so_locations \
--         _match.s maketree contrib/infback9/*.o
--      rm -rf objs
--      rm -f *.gcda *.gcno *.gcov
--      rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov
--
--maintainer-clean: distclean
--distclean: clean zconf zconf.h.cmakein docs
--      rm -f Makefile zlib.pc configure.log
--      -@rm -f .DS_Store
--      @if [ -f Makefile.in ]; then \
--      printf 'all:\n\t-@echo "Please use ./configure first.  Thank you."\n' > Makefile ; \
--      printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile ; \
--      touch -r $(SRCDIR)Makefile.in Makefile ; fi
--      @if [ ! -f zconf.h.in ]; then rm -f zconf.h zconf.h.cmakein ; fi
--      @if [ ! -f zlib.3 ]; then rm -f zlib.3.pdf ; fi
--
--tags:
--      etags $(SRCDIR)*.[ch]
--
--adler32.o zutil.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
--gzclose.o gzlib.o gzread.o gzwrite.o: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h
--compress.o example.o minigzip.o uncompr.o: $(SRCDIR)zlib.h zconf.h
--crc32.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h
--deflate.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
--infback.o inflate.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h
--inffast.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h
--inftrees.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h
--trees.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h
--
--adler32.lo zutil.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
--gzclose.lo gzlib.lo gzread.lo gzwrite.lo: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h
--compress.lo example.lo minigzip.lo uncompr.lo: $(SRCDIR)zlib.h zconf.h
--crc32.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h
--deflate.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
--infback.lo inflate.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h
--inffast.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h
--inftrees.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h
--trees.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h
diff --cc zlib/README
index 51106de4753292ad59de03de9e634e6814eeb7a2,51106de4753292ad59de03de9e634e6814eeb7a2..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,115 -1,115 +1,0 @@@
--ZLIB DATA COMPRESSION LIBRARY
--
--zlib 1.2.11 is a general purpose data compression library.  All the code is
--thread safe.  The data format used by the zlib library is described by RFCs
--(Request for Comments) 1950 to 1952 in the files
--http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
--rfc1952 (gzip format).
--
--All functions of the compression library are documented in the file zlib.h
--(volunteer to write man pages welcome, contact zlib@gzip.org).  A usage example
--of the library is given in the file test/example.c which also tests that
--the library is working correctly.  Another example is given in the file
--test/minigzip.c.  The compression library itself is composed of all source
--files in the root directory.
--
--To compile all files and run the test program, follow the instructions given at
--the top of Makefile.in.  In short "./configure; make test", and if that goes
--well, "make install" should work for most flavors of Unix.  For Windows, use
--one of the special makefiles in win32/ or contrib/vstudio/ .  For VMS, use
--make_vms.com.
--
--Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
--<info@winimage.com> for the Windows DLL version.  The zlib home page is
--http://zlib.net/ .  Before reporting a problem, please check this site to
--verify that you have the latest version of zlib; otherwise get the latest
--version and check whether the problem still exists or not.
--
--PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
--
--Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan.  1997
--issue of Dr.  Dobb's Journal; a copy of the article is available at
--http://marknelson.us/1997/01/01/zlib-engine/ .
--
--The changes made in version 1.2.11 are documented in the file ChangeLog.
--
--Unsupported third party contributions are provided in directory contrib/ .
--
--zlib is available in Java using the java.util.zip package, documented at
--http://java.sun.com/developer/technicalArticles/Programming/compression/ .
--
--A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is available
--at CPAN (Comprehensive Perl Archive Network) sites, including
--http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
--
--A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
--available in Python 1.5 and later versions, see
--http://docs.python.org/library/zlib.html .
--
--zlib is built into tcl: http://wiki.tcl.tk/4610 .
--
--An experimental package to read and write files in .zip format, written on top
--of zlib by Gilles Vollant <info@winimage.com>, is available in the
--contrib/minizip directory of zlib.
--
--
--Notes for some targets:
--
--- For Windows DLL versions, please see win32/DLL_FAQ.txt
--
--- For 64-bit Irix, deflate.c must be compiled without any optimization. With
--  -O, one libpng test fails. The test works in 32 bit mode (with the -n32
--  compiler flag). The compiler bug has been reported to SGI.
--
--- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
--  when compiled with cc.
--
--- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
--  necessary to get gzprintf working correctly. This is done by configure.
--
--- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
--  other compilers. Use "make test" to check your compiler.
--
--- gzdopen is not supported on RISCOS or BEOS.
--
--- For PalmOs, see http://palmzlib.sourceforge.net/
--
--
--Acknowledgments:
--
--  The deflate format used by zlib was defined by Phil Katz.  The deflate and
--  zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
--  people who reported problems and suggested various improvements in zlib; they
--  are too numerous to cite here.
--
--Copyright notice:
--
-- (C) 1995-2017 Jean-loup Gailly and Mark Adler
--
--  This software is provided 'as-is', without any express or implied
--  warranty.  In no event will the authors be held liable for any damages
--  arising from the use of this software.
--
--  Permission is granted to anyone to use this software for any purpose,
--  including commercial applications, and to alter it and redistribute it
--  freely, subject to the following restrictions:
--
--  1. The origin of this software must not be misrepresented; you must not
--     claim that you wrote the original software. If you use this software
--     in a product, an acknowledgment in the product documentation would be
--     appreciated but is not required.
--  2. Altered source versions must be plainly marked as such, and must not be
--     misrepresented as being the original software.
--  3. This notice may not be removed or altered from any source distribution.
--
--  Jean-loup Gailly        Mark Adler
--  jloup@gzip.org          madler@alumni.caltech.edu
--
--If you use the zlib library in a product, we would appreciate *not* receiving
--lengthy legal documents to sign.  The sources are provided for free but without
--warranty of any kind.  The library has been entirely written by Jean-loup
--Gailly and Mark Adler; it does not include third-party code.
--
--If you redistribute modified sources, we would appreciate that you include in
--the file ChangeLog history information documenting your changes.  Please read
--the FAQ for more information on the distribution of modified source versions.
diff --cc zlib/README.gpsbabel
index 1f9e687a391fb561b3c3dad98d0dddd97d8d72a2,3451fe85944ca887502b5f721046729933aac6f9..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,7 -1,6 +1,0 @@@
--modified subset of zlib-1.2.11 from zlib.net.
--note that zlib 1.2.8 has a seek bug that will bite us.
--other changes after zlib 1.2.8 may be required as well.
- 1. zconf.h is modified to include our config.h
- 2. contrib/minizip/ioapi.c modifies a conditional adding __CYGWIN__
- 3. contrib/minizip/ioapi.h modifies a conditional adding __FreeBSD__
 -1. contrib/minizip/ioapi.c modifies a conditional adding __CYGWIN__
 -2. contrib/minizip/ioapi.h modifies a conditional adding __FreeBSD__
--See the corresponding .patch files.
diff --cc zlib/adler32.c
index d0be4380a39c9c5bf439b1552c43585b5aafad0a,d0be4380a39c9c5bf439b1552c43585b5aafad0a..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,186 -1,186 +1,0 @@@
--/* adler32.c -- compute the Adler-32 checksum of a data stream
-- * Copyright (C) 1995-2011, 2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* @(#) $Id$ */
--
--#include "zutil.h"
--
--local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
--
--#define BASE 65521U     /* largest prime smaller than 65536 */
--#define NMAX 5552
--/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
--
--#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
--#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
--#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
--#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
--#define DO16(buf)   DO8(buf,0); DO8(buf,8);
--
--/* use NO_DIVIDE if your processor does not do division in hardware --
--   try it both ways to see which is faster */
--#ifdef NO_DIVIDE
--/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
--   (thank you to John Reiser for pointing this out) */
--#  define CHOP(a) \
--    do { \
--        unsigned long tmp = a >> 16; \
--        a &= 0xffffUL; \
--        a += (tmp << 4) - tmp; \
--    } while (0)
--#  define MOD28(a) \
--    do { \
--        CHOP(a); \
--        if (a >= BASE) a -= BASE; \
--    } while (0)
--#  define MOD(a) \
--    do { \
--        CHOP(a); \
--        MOD28(a); \
--    } while (0)
--#  define MOD63(a) \
--    do { /* this assumes a is not negative */ \
--        z_off64_t tmp = a >> 32; \
--        a &= 0xffffffffL; \
--        a += (tmp << 8) - (tmp << 5) + tmp; \
--        tmp = a >> 16; \
--        a &= 0xffffL; \
--        a += (tmp << 4) - tmp; \
--        tmp = a >> 16; \
--        a &= 0xffffL; \
--        a += (tmp << 4) - tmp; \
--        if (a >= BASE) a -= BASE; \
--    } while (0)
--#else
--#  define MOD(a) a %= BASE
--#  define MOD28(a) a %= BASE
--#  define MOD63(a) a %= BASE
--#endif
--
--/* ========================================================================= */
--uLong ZEXPORT adler32_z(adler, buf, len)
--    uLong adler;
--    const Bytef *buf;
--    z_size_t len;
--{
--    unsigned long sum2;
--    unsigned n;
--
--    /* split Adler-32 into component sums */
--    sum2 = (adler >> 16) & 0xffff;
--    adler &= 0xffff;
--
--    /* in case user likes doing a byte at a time, keep it fast */
--    if (len == 1) {
--        adler += buf[0];
--        if (adler >= BASE)
--            adler -= BASE;
--        sum2 += adler;
--        if (sum2 >= BASE)
--            sum2 -= BASE;
--        return adler | (sum2 << 16);
--    }
--
--    /* initial Adler-32 value (deferred check for len == 1 speed) */
--    if (buf == Z_NULL)
--        return 1L;
--
--    /* in case short lengths are provided, keep it somewhat fast */
--    if (len < 16) {
--        while (len--) {
--            adler += *buf++;
--            sum2 += adler;
--        }
--        if (adler >= BASE)
--            adler -= BASE;
--        MOD28(sum2);            /* only added so many BASE's */
--        return adler | (sum2 << 16);
--    }
--
--    /* do length NMAX blocks -- requires just one modulo operation */
--    while (len >= NMAX) {
--        len -= NMAX;
--        n = NMAX / 16;          /* NMAX is divisible by 16 */
--        do {
--            DO16(buf);          /* 16 sums unrolled */
--            buf += 16;
--        } while (--n);
--        MOD(adler);
--        MOD(sum2);
--    }
--
--    /* do remaining bytes (less than NMAX, still just one modulo) */
--    if (len) {                  /* avoid modulos if none remaining */
--        while (len >= 16) {
--            len -= 16;
--            DO16(buf);
--            buf += 16;
--        }
--        while (len--) {
--            adler += *buf++;
--            sum2 += adler;
--        }
--        MOD(adler);
--        MOD(sum2);
--    }
--
--    /* return recombined sums */
--    return adler | (sum2 << 16);
--}
--
--/* ========================================================================= */
--uLong ZEXPORT adler32(adler, buf, len)
--    uLong adler;
--    const Bytef *buf;
--    uInt len;
--{
--    return adler32_z(adler, buf, len);
--}
--
--/* ========================================================================= */
--local uLong adler32_combine_(adler1, adler2, len2)
--    uLong adler1;
--    uLong adler2;
--    z_off64_t len2;
--{
--    unsigned long sum1;
--    unsigned long sum2;
--    unsigned rem;
--
--    /* for negative len, return invalid adler32 as a clue for debugging */
--    if (len2 < 0)
--        return 0xffffffffUL;
--
--    /* the derivation of this formula is left as an exercise for the reader */
--    MOD63(len2);                /* assumes len2 >= 0 */
--    rem = (unsigned)len2;
--    sum1 = adler1 & 0xffff;
--    sum2 = rem * sum1;
--    MOD(sum2);
--    sum1 += (adler2 & 0xffff) + BASE - 1;
--    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
--    if (sum1 >= BASE) sum1 -= BASE;
--    if (sum1 >= BASE) sum1 -= BASE;
--    if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1);
--    if (sum2 >= BASE) sum2 -= BASE;
--    return sum1 | (sum2 << 16);
--}
--
--/* ========================================================================= */
--uLong ZEXPORT adler32_combine(adler1, adler2, len2)
--    uLong adler1;
--    uLong adler2;
--    z_off_t len2;
--{
--    return adler32_combine_(adler1, adler2, len2);
--}
--
--uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
--    uLong adler1;
--    uLong adler2;
--    z_off64_t len2;
--{
--    return adler32_combine_(adler1, adler2, len2);
--}
diff --cc zlib/algorithm.txt
index c97f495020b4293ee09994143ed6cd9d1bd0a2bf,c97f495020b4293ee09994143ed6cd9d1bd0a2bf..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,209 -1,209 +1,0 @@@
--1. Compression algorithm (deflate)
--
--The deflation algorithm used by gzip (also zip and zlib) is a variation of
--LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
--the input data.  The second occurrence of a string is replaced by a
--pointer to the previous string, in the form of a pair (distance,
--length).  Distances are limited to 32K bytes, and lengths are limited
--to 258 bytes. When a string does not occur anywhere in the previous
--32K bytes, it is emitted as a sequence of literal bytes.  (In this
--description, `string' must be taken as an arbitrary sequence of bytes,
--and is not restricted to printable characters.)
--
--Literals or match lengths are compressed with one Huffman tree, and
--match distances are compressed with another tree. The trees are stored
--in a compact form at the start of each block. The blocks can have any
--size (except that the compressed data for one block must fit in
--available memory). A block is terminated when deflate() determines that
--it would be useful to start another block with fresh trees. (This is
--somewhat similar to the behavior of LZW-based _compress_.)
--
--Duplicated strings are found using a hash table. All input strings of
--length 3 are inserted in the hash table. A hash index is computed for
--the next 3 bytes. If the hash chain for this index is not empty, all
--strings in the chain are compared with the current input string, and
--the longest match is selected.
--
--The hash chains are searched starting with the most recent strings, to
--favor small distances and thus take advantage of the Huffman encoding.
--The hash chains are singly linked. There are no deletions from the
--hash chains, the algorithm simply discards matches that are too old.
--
--To avoid a worst-case situation, very long hash chains are arbitrarily
--truncated at a certain length, determined by a runtime option (level
--parameter of deflateInit). So deflate() does not always find the longest
--possible match but generally finds a match which is long enough.
--
--deflate() also defers the selection of matches with a lazy evaluation
--mechanism. After a match of length N has been found, deflate() searches for
--a longer match at the next input byte. If a longer match is found, the
--previous match is truncated to a length of one (thus producing a single
--literal byte) and the process of lazy evaluation begins again. Otherwise,
--the original match is kept, and the next match search is attempted only N
--steps later.
--
--The lazy match evaluation is also subject to a runtime parameter. If
--the current match is long enough, deflate() reduces the search for a longer
--match, thus speeding up the whole process. If compression ratio is more
--important than speed, deflate() attempts a complete second search even if
--the first match is already long enough.
--
--The lazy match evaluation is not performed for the fastest compression
--modes (level parameter 1 to 3). For these fast modes, new strings
--are inserted in the hash table only when no match was found, or
--when the match is not too long. This degrades the compression ratio
--but saves time since there are both fewer insertions and fewer searches.
--
--
--2. Decompression algorithm (inflate)
--
--2.1 Introduction
--
--The key question is how to represent a Huffman code (or any prefix code) so
--that you can decode fast.  The most important characteristic is that shorter
--codes are much more common than longer codes, so pay attention to decoding the
--short codes fast, and let the long codes take longer to decode.
--
--inflate() sets up a first level table that covers some number of bits of
--input less than the length of longest code.  It gets that many bits from the
--stream, and looks it up in the table.  The table will tell if the next
--code is that many bits or less and how many, and if it is, it will tell
--the value, else it will point to the next level table for which inflate()
--grabs more bits and tries to decode a longer code.
--
--How many bits to make the first lookup is a tradeoff between the time it
--takes to decode and the time it takes to build the table.  If building the
--table took no time (and if you had infinite memory), then there would only
--be a first level table to cover all the way to the longest code.  However,
--building the table ends up taking a lot longer for more bits since short
--codes are replicated many times in such a table.  What inflate() does is
--simply to make the number of bits in the first table a variable, and  then
--to set that variable for the maximum speed.
--
--For inflate, which has 286 possible codes for the literal/length tree, the size
--of the first table is nine bits.  Also the distance trees have 30 possible
--values, and the size of the first table is six bits.  Note that for each of
--those cases, the table ended up one bit longer than the ``average'' code
--length, i.e. the code length of an approximately flat code which would be a
--little more than eight bits for 286 symbols and a little less than five bits
--for 30 symbols.
--
--
--2.2 More details on the inflate table lookup
--
--Ok, you want to know what this cleverly obfuscated inflate tree actually
--looks like.  You are correct that it's not a Huffman tree.  It is simply a
--lookup table for the first, let's say, nine bits of a Huffman symbol.  The
--symbol could be as short as one bit or as long as 15 bits.  If a particular
--symbol is shorter than nine bits, then that symbol's translation is duplicated
--in all those entries that start with that symbol's bits.  For example, if the
--symbol is four bits, then it's duplicated 32 times in a nine-bit table.  If a
--symbol is nine bits long, it appears in the table once.
--
--If the symbol is longer than nine bits, then that entry in the table points
--to another similar table for the remaining bits.  Again, there are duplicated
--entries as needed.  The idea is that most of the time the symbol will be short
--and there will only be one table look up.  (That's whole idea behind data
--compression in the first place.)  For the less frequent long symbols, there
--will be two lookups.  If you had a compression method with really long
--symbols, you could have as many levels of lookups as is efficient.  For
--inflate, two is enough.
--
--So a table entry either points to another table (in which case nine bits in
--the above example are gobbled), or it contains the translation for the symbol
--and the number of bits to gobble.  Then you start again with the next
--ungobbled bit.
--
--You may wonder: why not just have one lookup table for how ever many bits the
--longest symbol is?  The reason is that if you do that, you end up spending
--more time filling in duplicate symbol entries than you do actually decoding.
--At least for deflate's output that generates new trees every several 10's of
--kbytes.  You can imagine that filling in a 2^15 entry table for a 15-bit code
--would take too long if you're only decoding several thousand symbols.  At the
--other extreme, you could make a new table for every bit in the code.  In fact,
--that's essentially a Huffman tree.  But then you spend too much time
--traversing the tree while decoding, even for short symbols.
--
--So the number of bits for the first lookup table is a trade of the time to
--fill out the table vs. the time spent looking at the second level and above of
--the table.
--
--Here is an example, scaled down:
--
--The code being decoded, with 10 symbols, from 1 to 6 bits long:
--
--A: 0
--B: 10
--C: 1100
--D: 11010
--E: 11011
--F: 11100
--G: 11101
--H: 11110
--I: 111110
--J: 111111
--
--Let's make the first table three bits long (eight entries):
--
--000: A,1
--001: A,1
--010: A,1
--011: A,1
--100: B,2
--101: B,2
--110: -> table X (gobble 3 bits)
--111: -> table Y (gobble 3 bits)
--
--Each entry is what the bits decode as and how many bits that is, i.e. how
--many bits to gobble.  Or the entry points to another table, with the number of
--bits to gobble implicit in the size of the table.
--
--Table X is two bits long since the longest code starting with 110 is five bits
--long:
--
--00: C,1
--01: C,1
--10: D,2
--11: E,2
--
--Table Y is three bits long since the longest code starting with 111 is six
--bits long:
--
--000: F,2
--001: F,2
--010: G,2
--011: G,2
--100: H,2
--101: H,2
--110: I,3
--111: J,3
--
--So what we have here are three tables with a total of 20 entries that had to
--be constructed.  That's compared to 64 entries for a single table.  Or
--compared to 16 entries for a Huffman tree (six two entry tables and one four
--entry table).  Assuming that the code ideally represents the probability of
--the symbols, it takes on the average 1.25 lookups per symbol.  That's compared
--to one lookup for the single table, or 1.66 lookups per symbol for the
--Huffman tree.
--
--There, I think that gives you a picture of what's going on.  For inflate, the
--meaning of a particular symbol is often more than just a letter.  It can be a
--byte (a "literal"), or it can be either a length or a distance which
--indicates a base value and a number of bits to fetch after the code that is
--added to the base value.  Or it might be the special end-of-block code.  The
--data structures created in inftrees.c try to encode all that information
--compactly in the tables.
--
--
--Jean-loup Gailly        Mark Adler
--jloup@gzip.org          madler@alumni.caltech.edu
--
--
--References:
--
--[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
--Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
--pp. 337-343.
--
--``DEFLATE Compressed Data Format Specification'' available in
--http://tools.ietf.org/html/rfc1951
diff --cc zlib/compress.c
index e2db404abf888bd2c85844985b5ae9784b955c63,e2db404abf888bd2c85844985b5ae9784b955c63..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,86 -1,86 +1,0 @@@
--/* compress.c -- compress a memory buffer
-- * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* @(#) $Id$ */
--
--#define ZLIB_INTERNAL
--#include "zlib.h"
--
--/* ===========================================================================
--     Compresses the source buffer into the destination buffer. The level
--   parameter has the same meaning as in deflateInit.  sourceLen is the byte
--   length of the source buffer. Upon entry, destLen is the total size of the
--   destination buffer, which must be at least 0.1% larger than sourceLen plus
--   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
--
--     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
--   Z_STREAM_ERROR if the level parameter is invalid.
--*/
--int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
--    Bytef *dest;
--    uLongf *destLen;
--    const Bytef *source;
--    uLong sourceLen;
--    int level;
--{
--    z_stream stream;
--    int err;
--    const uInt max = (uInt)-1;
--    uLong left;
--
--    left = *destLen;
--    *destLen = 0;
--
--    stream.zalloc = (alloc_func)0;
--    stream.zfree = (free_func)0;
--    stream.opaque = (voidpf)0;
--
--    err = deflateInit(&stream, level);
--    if (err != Z_OK) return err;
--
--    stream.next_out = dest;
--    stream.avail_out = 0;
--    stream.next_in = (z_const Bytef *)source;
--    stream.avail_in = 0;
--
--    do {
--        if (stream.avail_out == 0) {
--            stream.avail_out = left > (uLong)max ? max : (uInt)left;
--            left -= stream.avail_out;
--        }
--        if (stream.avail_in == 0) {
--            stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;
--            sourceLen -= stream.avail_in;
--        }
--        err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
--    } while (err == Z_OK);
--
--    *destLen = stream.total_out;
--    deflateEnd(&stream);
--    return err == Z_STREAM_END ? Z_OK : err;
--}
--
--/* ===========================================================================
-- */
--int ZEXPORT compress (dest, destLen, source, sourceLen)
--    Bytef *dest;
--    uLongf *destLen;
--    const Bytef *source;
--    uLong sourceLen;
--{
--    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
--}
--
--/* ===========================================================================
--     If the default memLevel or windowBits for deflateInit() is changed, then
--   this function needs to be updated.
-- */
--uLong ZEXPORT compressBound (sourceLen)
--    uLong sourceLen;
--{
--    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
--           (sourceLen >> 25) + 13;
--}
diff --cc zlib/contrib/minizip/Makefile
index 84eaad20d4fb19b00965268dd75d7e9b66c8cc21,84eaad20d4fb19b00965268dd75d7e9b66c8cc21..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,25 -1,25 +1,0 @@@
--CC=cc
--CFLAGS=-O -I../..
--
--UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a
--ZIP_OBJS = minizip.o zip.o   ioapi.o ../../libz.a
--
--.c.o:
--      $(CC) -c $(CFLAGS) $*.c
--
--all: miniunz minizip
--
--miniunz:  $(UNZ_OBJS)
--      $(CC) $(CFLAGS) -o $@ $(UNZ_OBJS)
--
--minizip:  $(ZIP_OBJS)
--      $(CC) $(CFLAGS) -o $@ $(ZIP_OBJS)
--
--test: miniunz minizip
--      ./minizip test readme.txt
--      ./miniunz -l test.zip
--      mv readme.txt readme.old
--      ./miniunz test.zip
--
--clean:
--      /bin/rm -f *.o *~ minizip miniunz
diff --cc zlib/contrib/minizip/Makefile.am
index d343011ebc3b3fd78d2bc3a29801a083c038cf0c,d343011ebc3b3fd78d2bc3a29801a083c038cf0c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,45 -1,45 +1,0 @@@
--lib_LTLIBRARIES = libminizip.la
--
--if COND_DEMOS
--bin_PROGRAMS = miniunzip minizip
--endif
--
--zlib_top_srcdir = $(top_srcdir)/../..
--zlib_top_builddir = $(top_builddir)/../..
--
--AM_CPPFLAGS = -I$(zlib_top_srcdir)
--AM_LDFLAGS = -L$(zlib_top_builddir)
--
--if WIN32
--iowin32_src = iowin32.c
--iowin32_h = iowin32.h
--endif
--
--libminizip_la_SOURCES = \
--      ioapi.c \
--      mztools.c \
--      unzip.c \
--      zip.c \
--      ${iowin32_src}
--
--libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz
--
--minizip_includedir = $(includedir)/minizip
--minizip_include_HEADERS = \
--      crypt.h \
--      ioapi.h \
--      mztools.h \
--      unzip.h \
--      zip.h \
--      ${iowin32_h}
--
--pkgconfigdir = $(libdir)/pkgconfig
--pkgconfig_DATA = minizip.pc
--
--EXTRA_PROGRAMS = miniunzip minizip
--
--miniunzip_SOURCES = miniunz.c
--miniunzip_LDADD = libminizip.la
--
--minizip_SOURCES = minizip.c
--minizip_LDADD = libminizip.la -lz
diff --cc zlib/contrib/minizip/MiniZip64_Changes.txt
index 13a1bd91a9b00f5527e7878e74740918d2833907,13a1bd91a9b00f5527e7878e74740918d2833907..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,6 -1,6 +1,0 @@@
--
--MiniZip 1.1 was derrived from MiniZip at version 1.01f
--
--Change in 1.0 (Okt 2009)
-- - **TODO - Add history**
--
diff --cc zlib/contrib/minizip/MiniZip64_info.txt
index 57d715242087b328c37dbd6a47217b63b1ed88c6,57d715242087b328c37dbd6a47217b63b1ed88c6..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,74 -1,74 +1,0 @@@
--MiniZip - Copyright (c) 1998-2010 - by Gilles Vollant - version 1.1 64 bits from Mathias Svensson
--
--Introduction
-----------------------
--MiniZip 1.1 is built from MiniZip 1.0 by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html )
--
--When adding ZIP64 support into minizip it would result into risk of breaking compatibility with minizip 1.0.
--All possible work was done for compatibility.
--
--
--Background
-----------------------
--When adding ZIP64 support Mathias Svensson found that Even Rouault have added ZIP64 
--support for unzip.c into minizip for a open source project called gdal ( http://www.gdal.org/ )
--
--That was used as a starting point. And after that ZIP64 support was added to zip.c
--some refactoring and code cleanup was also done.
--
--
--Changed from MiniZip 1.0 to MiniZip 1.1
-----------------------------------------
--* Added ZIP64 support for unzip ( by Even Rouault )
--* Added ZIP64 support for zip ( by Mathias Svensson )
--* Reverted some changed that Even Rouault did.
--* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users.
--* Added unzip patch for BZIP Compression method (patch create by Daniel Borca)
--* Added BZIP Compress method for zip
--* Did some refactoring and code cleanup
--
--
--Credits
--
-- Gilles Vollant    - Original MiniZip author
-- Even Rouault      - ZIP64 unzip Support
-- Daniel Borca      - BZip Compression method support in unzip
-- Mathias Svensson  - ZIP64 zip support
-- Mathias Svensson  - BZip Compression method support in zip
--
-- Resources
--
-- ZipLayout   http://result42.com/projects/ZipFileLayout
--             Command line tool for Windows that shows the layout and information of the headers in a zip archive.
--             Used when debugging and validating the creation of zip files using MiniZip64
--
--
-- ZIP App Note  http://www.pkware.com/documents/casestudies/APPNOTE.TXT
--               Zip File specification
--
--
--Notes.
-- * To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined.
--
--License
------------------------------------------------------------
--   Condition of use and distribution are the same than zlib :
--
--  This software is provided 'as-is', without any express or implied
--  warranty.  In no event will the authors be held liable for any damages
--  arising from the use of this software.
--
--  Permission is granted to anyone to use this software for any purpose,
--  including commercial applications, and to alter it and redistribute it
--  freely, subject to the following restrictions:
--
--  1. The origin of this software must not be misrepresented; you must not
--     claim that you wrote the original software. If you use this software
--     in a product, an acknowledgment in the product documentation would be
--     appreciated but is not required.
--  2. Altered source versions must be plainly marked as such, and must not be
--     misrepresented as being the original software.
--  3. This notice may not be removed or altered from any source distribution.
--
------------------------------------------------------------
--
diff --cc zlib/contrib/minizip/configure.ac
index 5b11970977f03d8ffdc48aa985bc07d1dddbcedd,5b11970977f03d8ffdc48aa985bc07d1dddbcedd..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,32 -1,32 +1,0 @@@
--#                                               -*- Autoconf -*-
--# Process this file with autoconf to produce a configure script.
--
--AC_INIT([minizip], [1.2.11], [bugzilla.redhat.com])
--AC_CONFIG_SRCDIR([minizip.c])
--AM_INIT_AUTOMAKE([foreign])
--LT_INIT
--
--AC_MSG_CHECKING([whether to build example programs])
--AC_ARG_ENABLE([demos], AC_HELP_STRING([--enable-demos], [build example programs]))
--AM_CONDITIONAL([COND_DEMOS], [test "$enable_demos" = yes])
--if test "$enable_demos" = yes
--then
--      AC_MSG_RESULT([yes])
--else
--      AC_MSG_RESULT([no])
--fi
--
--case "${host}" in
--      *-mingw* | mingw*)
--              WIN32="yes"
--              ;;
--      *)
--              ;;
--esac
--AM_CONDITIONAL([WIN32], [test "${WIN32}" = "yes"])
--
--
--AC_SUBST([HAVE_UNISTD_H], [0])
--AC_CHECK_HEADER([unistd.h], [HAVE_UNISTD_H=1], [])
--AC_CONFIG_FILES([Makefile minizip.pc])
--AC_OUTPUT
diff --cc zlib/contrib/minizip/crypt.h
index 1e9e8200b201ff600aecd9eb7df1ac6989931266,1e9e8200b201ff600aecd9eb7df1ac6989931266..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,131 -1,131 +1,0 @@@
--/* crypt.h -- base code for crypt/uncrypt ZIPfile
--
--
--   Version 1.01e, February 12th, 2005
--
--   Copyright (C) 1998-2005 Gilles Vollant
--
--   This code is a modified version of crypting code in Infozip distribution
--
--   The encryption/decryption parts of this source code (as opposed to the
--   non-echoing password parts) were originally written in Europe.  The
--   whole source package can be freely distributed, including from the USA.
--   (Prior to January 2000, re-export from the US was a violation of US law.)
--
--   This encryption code is a direct transcription of the algorithm from
--   Roger Schlafly, described by Phil Katz in the file appnote.txt.  This
--   file (appnote.txt) is distributed with the PKZIP program (even in the
--   version without encryption capabilities).
--
--   If you don't need crypting in your application, just define symbols
--   NOCRYPT and NOUNCRYPT.
--
--   This code support the "Traditional PKWARE Encryption".
--
--   The new AES encryption added on Zip format by Winzip (see the page
--   http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
--   Encryption is not supported.
--*/
--
--#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
--
--/***********************************************************************
-- * Return the next byte in the pseudo-random sequence
-- */
--static int decrypt_byte(unsigned long* pkeys, const z_crc_t* pcrc_32_tab)
--{
--    unsigned temp;  /* POTENTIAL BUG:  temp*(temp^1) may overflow in an
--                     * unpredictable manner on 16-bit systems; not a problem
--                     * with any known compiler so far, though */
--
--    temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
--    return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
--}
--
--/***********************************************************************
-- * Update the encryption keys with the next byte of plain text
-- */
--static int update_keys(unsigned long* pkeys,const z_crc_t* pcrc_32_tab,int c)
--{
--    (*(pkeys+0)) = CRC32((*(pkeys+0)), c);
--    (*(pkeys+1)) += (*(pkeys+0)) & 0xff;
--    (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
--    {
--      register int keyshift = (int)((*(pkeys+1)) >> 24);
--      (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
--    }
--    return c;
--}
--
--
--/***********************************************************************
-- * Initialize the encryption keys and the random header according to
-- * the given password.
-- */
--static void init_keys(const char* passwd,unsigned long* pkeys,const z_crc_t* pcrc_32_tab)
--{
--    *(pkeys+0) = 305419896L;
--    *(pkeys+1) = 591751049L;
--    *(pkeys+2) = 878082192L;
--    while (*passwd != '\0') {
--        update_keys(pkeys,pcrc_32_tab,(int)*passwd);
--        passwd++;
--    }
--}
--
--#define zdecode(pkeys,pcrc_32_tab,c) \
--    (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
--
--#define zencode(pkeys,pcrc_32_tab,c,t) \
--    (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c))
--
--#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
--
--#define RAND_HEAD_LEN  12
--   /* "last resort" source for second part of crypt seed pattern */
--#  ifndef ZCR_SEED2
--#    define ZCR_SEED2 3141592654UL     /* use PI as default pattern */
--#  endif
--
--static int crypthead(const char* passwd,      /* password string */
--                     unsigned char* buf,      /* where to write header */
--                     int bufSize,
--                     unsigned long* pkeys,
--                     const z_crc_t* pcrc_32_tab,
--                     unsigned long crcForCrypting)
--{
--    int n;                       /* index in random header */
--    int t;                       /* temporary */
--    int c;                       /* random byte */
--    unsigned char header[RAND_HEAD_LEN-2]; /* random header */
--    static unsigned calls = 0;   /* ensure different random header each time */
--
--    if (bufSize<RAND_HEAD_LEN)
--      return 0;
--
--    /* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
--     * output of rand() to get less predictability, since rand() is
--     * often poorly implemented.
--     */
--    if (++calls == 1)
--    {
--        srand((unsigned)(time(NULL) ^ ZCR_SEED2));
--    }
--    init_keys(passwd, pkeys, pcrc_32_tab);
--    for (n = 0; n < RAND_HEAD_LEN-2; n++)
--    {
--        c = (rand() >> 7) & 0xff;
--        header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
--    }
--    /* Encrypt random header (last two bytes is high word of crc) */
--    init_keys(passwd, pkeys, pcrc_32_tab);
--    for (n = 0; n < RAND_HEAD_LEN-2; n++)
--    {
--        buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
--    }
--    buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
--    buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
--    return n;
--}
--
--#endif
diff --cc zlib/contrib/minizip/ioapi.c
index efb357918f54cc29b7c62271a7b28f7be78fdd71,efb357918f54cc29b7c62271a7b28f7be78fdd71..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,247 -1,247 +1,0 @@@
--/* ioapi.h -- IO base function header for compress/uncompress .zip
--   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications for Zip64 support
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--*/
--
--#if defined(_WIN32) && (!(defined(_CRT_SECURE_NO_WARNINGS)))
--        #define _CRT_SECURE_NO_WARNINGS
--#endif
--
--#if defined(__APPLE__) || defined(IOAPI_NO_64) || defined(__CYGWIN__)
--// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
--#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
--#define FTELLO_FUNC(stream) ftello(stream)
--#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
--#else
--#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
--#define FTELLO_FUNC(stream) ftello64(stream)
--#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
--#endif
--
--
--#include "ioapi.h"
--
--voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
--{
--    if (pfilefunc->zfile_func64.zopen64_file != NULL)
--        return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
--    else
--    {
--        return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
--    }
--}
--
--long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
--{
--    if (pfilefunc->zfile_func64.zseek64_file != NULL)
--        return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
--    else
--    {
--        uLong offsetTruncated = (uLong)offset;
--        if (offsetTruncated != offset)
--            return -1;
--        else
--            return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
--    }
--}
--
--ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
--{
--    if (pfilefunc->zfile_func64.zseek64_file != NULL)
--        return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
--    else
--    {
--        uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
--        if ((tell_uLong) == MAXU32)
--            return (ZPOS64_T)-1;
--        else
--            return tell_uLong;
--    }
--}
--
--void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
--{
--    p_filefunc64_32->zfile_func64.zopen64_file = NULL;
--    p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
--    p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
--    p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
--    p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
--    p_filefunc64_32->zfile_func64.ztell64_file = NULL;
--    p_filefunc64_32->zfile_func64.zseek64_file = NULL;
--    p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
--    p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
--    p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
--    p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
--    p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
--}
--
--
--
--static voidpf  ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
--static uLong   ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
--static uLong   ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
--static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
--static long    ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
--static int     ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
--static int     ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
--
--static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
--{
--    FILE* file = NULL;
--    const char* mode_fopen = NULL;
--    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
--        mode_fopen = "rb";
--    else
--    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
--        mode_fopen = "r+b";
--    else
--    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
--        mode_fopen = "wb";
--
--    if ((filename!=NULL) && (mode_fopen != NULL))
--        file = fopen(filename, mode_fopen);
--    return file;
--}
--
--static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
--{
--    FILE* file = NULL;
--    const char* mode_fopen = NULL;
--    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
--        mode_fopen = "rb";
--    else
--    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
--        mode_fopen = "r+b";
--    else
--    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
--        mode_fopen = "wb";
--
--    if ((filename!=NULL) && (mode_fopen != NULL))
--        file = FOPEN_FUNC((const char*)filename, mode_fopen);
--    return file;
--}
--
--
--static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
--{
--    uLong ret;
--    ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
--    return ret;
--}
--
--static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
--{
--    uLong ret;
--    ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
--    return ret;
--}
--
--static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
--{
--    long ret;
--    ret = ftell((FILE *)stream);
--    return ret;
--}
--
--
--static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
--{
--    ZPOS64_T ret;
--    ret = FTELLO_FUNC((FILE *)stream);
--    return ret;
--}
--
--static long ZCALLBACK fseek_file_func (voidpf  opaque, voidpf stream, uLong offset, int origin)
--{
--    int fseek_origin=0;
--    long ret;
--    switch (origin)
--    {
--    case ZLIB_FILEFUNC_SEEK_CUR :
--        fseek_origin = SEEK_CUR;
--        break;
--    case ZLIB_FILEFUNC_SEEK_END :
--        fseek_origin = SEEK_END;
--        break;
--    case ZLIB_FILEFUNC_SEEK_SET :
--        fseek_origin = SEEK_SET;
--        break;
--    default: return -1;
--    }
--    ret = 0;
--    if (fseek((FILE *)stream, offset, fseek_origin) != 0)
--        ret = -1;
--    return ret;
--}
--
--static long ZCALLBACK fseek64_file_func (voidpf  opaque, voidpf stream, ZPOS64_T offset, int origin)
--{
--    int fseek_origin=0;
--    long ret;
--    switch (origin)
--    {
--    case ZLIB_FILEFUNC_SEEK_CUR :
--        fseek_origin = SEEK_CUR;
--        break;
--    case ZLIB_FILEFUNC_SEEK_END :
--        fseek_origin = SEEK_END;
--        break;
--    case ZLIB_FILEFUNC_SEEK_SET :
--        fseek_origin = SEEK_SET;
--        break;
--    default: return -1;
--    }
--    ret = 0;
--
--    if(FSEEKO_FUNC((FILE *)stream, offset, fseek_origin) != 0)
--                        ret = -1;
--
--    return ret;
--}
--
--
--static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
--{
--    int ret;
--    ret = fclose((FILE *)stream);
--    return ret;
--}
--
--static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
--{
--    int ret;
--    ret = ferror((FILE *)stream);
--    return ret;
--}
--
--void fill_fopen_filefunc (pzlib_filefunc_def)
--  zlib_filefunc_def* pzlib_filefunc_def;
--{
--    pzlib_filefunc_def->zopen_file = fopen_file_func;
--    pzlib_filefunc_def->zread_file = fread_file_func;
--    pzlib_filefunc_def->zwrite_file = fwrite_file_func;
--    pzlib_filefunc_def->ztell_file = ftell_file_func;
--    pzlib_filefunc_def->zseek_file = fseek_file_func;
--    pzlib_filefunc_def->zclose_file = fclose_file_func;
--    pzlib_filefunc_def->zerror_file = ferror_file_func;
--    pzlib_filefunc_def->opaque = NULL;
--}
--
--void fill_fopen64_filefunc (zlib_filefunc64_def*  pzlib_filefunc_def)
--{
--    pzlib_filefunc_def->zopen64_file = fopen64_file_func;
--    pzlib_filefunc_def->zread_file = fread_file_func;
--    pzlib_filefunc_def->zwrite_file = fwrite_file_func;
--    pzlib_filefunc_def->ztell64_file = ftell64_file_func;
--    pzlib_filefunc_def->zseek64_file = fseek64_file_func;
--    pzlib_filefunc_def->zclose_file = fclose_file_func;
--    pzlib_filefunc_def->zerror_file = ferror_file_func;
--    pzlib_filefunc_def->opaque = NULL;
--}
diff --cc zlib/contrib/minizip/ioapi.c.patch
index 54f1b8f777e3dfc23adc4b0041af704860f5723f,54f1b8f777e3dfc23adc4b0041af704860f5723f..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,11 -1,11 +1,0 @@@
----- ../zlib-1.2.8/contrib/minizip/ioapi.c     2012-01-21 12:58:45.000000000 -0700
--+++ zlib/contrib/minizip/ioapi.c      2017-11-11 09:05:50.662012999 -0700
--@@ -14,7 +14,7 @@
--         #define _CRT_SECURE_NO_WARNINGS
-- #endif
-- 
---#if defined(__APPLE__) || defined(IOAPI_NO_64)
--+#if defined(__APPLE__) || defined(IOAPI_NO_64) || defined(__CYGWIN__)
-- // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
-- #define FOPEN_FUNC(filename, mode) fopen(filename, mode)
-- #define FTELLO_FUNC(stream) ftello(stream)
diff --cc zlib/contrib/minizip/ioapi.h
index 3b5d37baa3ac2069264e73db4192213cbd6768de,3b5d37baa3ac2069264e73db4192213cbd6768de..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,208 -1,208 +1,0 @@@
--/* ioapi.h -- IO base function header for compress/uncompress .zip
--   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications for Zip64 support
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--         Changes
--
--    Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
--    Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
--               More if/def section may be needed to support other platforms
--    Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
--                          (but you should use iowin32.c for windows instead)
--
--*/
--
--#ifndef _ZLIBIOAPI64_H
--#define _ZLIBIOAPI64_H
--
--#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
--
--  // Linux needs this to support file operation on files larger then 4+GB
--  // But might need better if/def to select just the platforms that needs them.
--
--        #ifndef __USE_FILE_OFFSET64
--                #define __USE_FILE_OFFSET64
--        #endif
--        #ifndef __USE_LARGEFILE64
--                #define __USE_LARGEFILE64
--        #endif
--        #ifndef _LARGEFILE64_SOURCE
--                #define _LARGEFILE64_SOURCE
--        #endif
--        #ifndef _FILE_OFFSET_BIT
--                #define _FILE_OFFSET_BIT 64
--        #endif
--
--#endif
--
--#include <stdio.h>
--#include <stdlib.h>
--#include "zlib.h"
--
--#if defined(USE_FILE32API)
--#define fopen64 fopen
--#define ftello64 ftell
--#define fseeko64 fseek
--#else
--#if defined(__FreeBSD__) || defined(__OpenBSD__)
--#define fopen64 fopen
--#define ftello64 ftello
--#define fseeko64 fseeko
--#endif
--#ifdef _MSC_VER
-- #define fopen64 fopen
-- #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
--  #define ftello64 _ftelli64
--  #define fseeko64 _fseeki64
-- #else // old MSC
--  #define ftello64 ftell
--  #define fseeko64 fseek
-- #endif
--#endif
--#endif
--
--/*
--#ifndef ZPOS64_T
--  #ifdef _WIN32
--                #define ZPOS64_T fpos_t
--  #else
--    #include <stdint.h>
--    #define ZPOS64_T uint64_t
--  #endif
--#endif
--*/
--
--#ifdef HAVE_MINIZIP64_CONF_H
--#include "mz64conf.h"
--#endif
--
--/* a type choosen by DEFINE */
--#ifdef HAVE_64BIT_INT_CUSTOM
--typedef  64BIT_INT_CUSTOM_TYPE ZPOS64_T;
--#else
--#ifdef HAS_STDINT_H
--#include "stdint.h"
--typedef uint64_t ZPOS64_T;
--#else
--
--/* Maximum unsigned 32-bit value used as placeholder for zip64 */
--#define MAXU32 0xffffffff
--
--#if defined(_MSC_VER) || defined(__BORLANDC__)
--typedef unsigned __int64 ZPOS64_T;
--#else
--typedef unsigned long long int ZPOS64_T;
--#endif
--#endif
--#endif
--
--
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--
--#define ZLIB_FILEFUNC_SEEK_CUR (1)
--#define ZLIB_FILEFUNC_SEEK_END (2)
--#define ZLIB_FILEFUNC_SEEK_SET (0)
--
--#define ZLIB_FILEFUNC_MODE_READ      (1)
--#define ZLIB_FILEFUNC_MODE_WRITE     (2)
--#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
--
--#define ZLIB_FILEFUNC_MODE_EXISTING (4)
--#define ZLIB_FILEFUNC_MODE_CREATE   (8)
--
--
--#ifndef ZCALLBACK
-- #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
--   #define ZCALLBACK CALLBACK
-- #else
--   #define ZCALLBACK
-- #endif
--#endif
--
--
--
--
--typedef voidpf   (ZCALLBACK *open_file_func)      OF((voidpf opaque, const char* filename, int mode));
--typedef uLong    (ZCALLBACK *read_file_func)      OF((voidpf opaque, voidpf stream, void* buf, uLong size));
--typedef uLong    (ZCALLBACK *write_file_func)     OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
--typedef int      (ZCALLBACK *close_file_func)     OF((voidpf opaque, voidpf stream));
--typedef int      (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
--
--typedef long     (ZCALLBACK *tell_file_func)      OF((voidpf opaque, voidpf stream));
--typedef long     (ZCALLBACK *seek_file_func)      OF((voidpf opaque, voidpf stream, uLong offset, int origin));
--
--
--/* here is the "old" 32 bits structure structure */
--typedef struct zlib_filefunc_def_s
--{
--    open_file_func      zopen_file;
--    read_file_func      zread_file;
--    write_file_func     zwrite_file;
--    tell_file_func      ztell_file;
--    seek_file_func      zseek_file;
--    close_file_func     zclose_file;
--    testerror_file_func zerror_file;
--    voidpf              opaque;
--} zlib_filefunc_def;
--
--typedef ZPOS64_T (ZCALLBACK *tell64_file_func)    OF((voidpf opaque, voidpf stream));
--typedef long     (ZCALLBACK *seek64_file_func)    OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
--typedef voidpf   (ZCALLBACK *open64_file_func)    OF((voidpf opaque, const void* filename, int mode));
--
--typedef struct zlib_filefunc64_def_s
--{
--    open64_file_func    zopen64_file;
--    read_file_func      zread_file;
--    write_file_func     zwrite_file;
--    tell64_file_func    ztell64_file;
--    seek64_file_func    zseek64_file;
--    close_file_func     zclose_file;
--    testerror_file_func zerror_file;
--    voidpf              opaque;
--} zlib_filefunc64_def;
--
--void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
--void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
--
--/* now internal definition, only for zip.c and unzip.h */
--typedef struct zlib_filefunc64_32_def_s
--{
--    zlib_filefunc64_def zfile_func64;
--    open_file_func      zopen32_file;
--    tell_file_func      ztell32_file;
--    seek_file_func      zseek32_file;
--} zlib_filefunc64_32_def;
--
--
--#define ZREAD64(filefunc,filestream,buf,size)     ((*((filefunc).zfile_func64.zread_file))   ((filefunc).zfile_func64.opaque,filestream,buf,size))
--#define ZWRITE64(filefunc,filestream,buf,size)    ((*((filefunc).zfile_func64.zwrite_file))  ((filefunc).zfile_func64.opaque,filestream,buf,size))
--//#define ZTELL64(filefunc,filestream)            ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
--//#define ZSEEK64(filefunc,filestream,pos,mode)   ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
--#define ZCLOSE64(filefunc,filestream)             ((*((filefunc).zfile_func64.zclose_file))  ((filefunc).zfile_func64.opaque,filestream))
--#define ZERROR64(filefunc,filestream)             ((*((filefunc).zfile_func64.zerror_file))  ((filefunc).zfile_func64.opaque,filestream))
--
--voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
--long    call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
--ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
--
--void    fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
--
--#define ZOPEN64(filefunc,filename,mode)         (call_zopen64((&(filefunc)),(filename),(mode)))
--#define ZTELL64(filefunc,filestream)            (call_ztell64((&(filefunc)),(filestream)))
--#define ZSEEK64(filefunc,filestream,pos,mode)   (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
--
--#ifdef __cplusplus
--}
--#endif
--
--#endif
diff --cc zlib/contrib/minizip/ioapi.h.patch
index c4c9c3e7ff3bd03ab965f0c2095920bd6e5b68fc,c4c9c3e7ff3bd03ab965f0c2095920bd6e5b68fc..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,11 -1,11 +1,0 @@@
----- ../zlib-1.2.8/contrib/minizip/ioapi.h     2012-01-16 19:51:31.000000000 -0700
--+++ zlib/contrib/minizip/ioapi.h      2017-11-11 09:05:50.662012999 -0700
--@@ -50,7 +50,7 @@
-- #define ftello64 ftell
-- #define fseeko64 fseek
-- #else
---#ifdef __FreeBSD__
--+#if defined(__FreeBSD__) || defined(__OpenBSD__)
-- #define fopen64 fopen
-- #define ftello64 ftello
-- #define fseeko64 fseeko
diff --cc zlib/contrib/minizip/iowin32.c
index 274f39eb1dd2c6d3252b50699da1a5673a25b0f8,274f39eb1dd2c6d3252b50699da1a5673a25b0f8..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,462 -1,462 +1,0 @@@
--/* iowin32.c -- IO base function header for compress/uncompress .zip
--     Version 1.1, February 14h, 2010
--     part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications for Zip64 support
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--     For more info read MiniZip_info.txt
--
--*/
--
--#include <stdlib.h>
--
--#include "zlib.h"
--#include "ioapi.h"
--#include "iowin32.h"
--
--#ifndef INVALID_HANDLE_VALUE
--#define INVALID_HANDLE_VALUE (0xFFFFFFFF)
--#endif
--
--#ifndef INVALID_SET_FILE_POINTER
--#define INVALID_SET_FILE_POINTER ((DWORD)-1)
--#endif
--
--
--// see Include/shared/winapifamily.h in the Windows Kit
--#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API)))
--#if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP)
--#define IOWIN32_USING_WINRT_API 1
--#endif
--#endif
--
--voidpf  ZCALLBACK win32_open_file_func  OF((voidpf opaque, const char* filename, int mode));
--uLong   ZCALLBACK win32_read_file_func  OF((voidpf opaque, voidpf stream, void* buf, uLong size));
--uLong   ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
--ZPOS64_T ZCALLBACK win32_tell64_file_func  OF((voidpf opaque, voidpf stream));
--long    ZCALLBACK win32_seek64_file_func  OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
--int     ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream));
--int     ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream));
--
--typedef struct
--{
--    HANDLE hf;
--    int error;
--} WIN32FILE_IOWIN;
--
--
--static void win32_translate_open_mode(int mode,
--                                      DWORD* lpdwDesiredAccess,
--                                      DWORD* lpdwCreationDisposition,
--                                      DWORD* lpdwShareMode,
--                                      DWORD* lpdwFlagsAndAttributes)
--{
--    *lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0;
--
--    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
--    {
--        *lpdwDesiredAccess = GENERIC_READ;
--        *lpdwCreationDisposition = OPEN_EXISTING;
--        *lpdwShareMode = FILE_SHARE_READ;
--    }
--    else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
--    {
--        *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
--        *lpdwCreationDisposition = OPEN_EXISTING;
--    }
--    else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
--    {
--        *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
--        *lpdwCreationDisposition = CREATE_ALWAYS;
--    }
--}
--
--static voidpf win32_build_iowin(HANDLE hFile)
--{
--    voidpf ret=NULL;
--
--    if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
--    {
--        WIN32FILE_IOWIN w32fiow;
--        w32fiow.hf = hFile;
--        w32fiow.error = 0;
--        ret = malloc(sizeof(WIN32FILE_IOWIN));
--
--        if (ret==NULL)
--            CloseHandle(hFile);
--        else
--            *((WIN32FILE_IOWIN*)ret) = w32fiow;
--    }
--    return ret;
--}
--
--voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode)
--{
--    const char* mode_fopen = NULL;
--    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
--    HANDLE hFile = NULL;
--
--    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
--
--#ifdef IOWIN32_USING_WINRT_API
--#ifdef UNICODE
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
--#else
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--    {
--        WCHAR filenameW[FILENAME_MAX + 0x200 + 1];
--        MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200);
--        hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
--    }
--#endif
--#else
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
--#endif
--
--    return win32_build_iowin(hFile);
--}
--
--
--voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode)
--{
--    const char* mode_fopen = NULL;
--    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
--    HANDLE hFile = NULL;
--
--    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
--
--#ifdef IOWIN32_USING_WINRT_API
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--    {
--        WCHAR filenameW[FILENAME_MAX + 0x200 + 1];
--        MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200);
--        hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
--    }
--#else
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
--#endif
--
--    return win32_build_iowin(hFile);
--}
--
--
--voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode)
--{
--    const char* mode_fopen = NULL;
--    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
--    HANDLE hFile = NULL;
--
--    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
--
--#ifdef IOWIN32_USING_WINRT_API
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition,NULL);
--#else
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
--#endif
--
--    return win32_build_iowin(hFile);
--}
--
--
--voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode)
--{
--    const char* mode_fopen = NULL;
--    DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
--    HANDLE hFile = NULL;
--
--    win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
--
--#ifdef IOWIN32_USING_WINRT_API
--#ifdef UNICODE
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
--#else
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--    {
--        WCHAR filenameW[FILENAME_MAX + 0x200 + 1];
--        MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200);
--        hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
--    }
--#endif
--#else
--    if ((filename!=NULL) && (dwDesiredAccess != 0))
--        hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
--#endif
--
--    return win32_build_iowin(hFile);
--}
--
--
--uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
--{
--    uLong ret=0;
--    HANDLE hFile = NULL;
--    if (stream!=NULL)
--        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
--
--    if (hFile != NULL)
--    {
--        if (!ReadFile(hFile, buf, size, &ret, NULL))
--        {
--            DWORD dwErr = GetLastError();
--            if (dwErr == ERROR_HANDLE_EOF)
--                dwErr = 0;
--            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
--        }
--    }
--
--    return ret;
--}
--
--
--uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
--{
--    uLong ret=0;
--    HANDLE hFile = NULL;
--    if (stream!=NULL)
--        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
--
--    if (hFile != NULL)
--    {
--        if (!WriteFile(hFile, buf, size, &ret, NULL))
--        {
--            DWORD dwErr = GetLastError();
--            if (dwErr == ERROR_HANDLE_EOF)
--                dwErr = 0;
--            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
--        }
--    }
--
--    return ret;
--}
--
--static BOOL MySetFilePointerEx(HANDLE hFile, LARGE_INTEGER pos, LARGE_INTEGER *newPos,  DWORD dwMoveMethod)
--{
--#ifdef IOWIN32_USING_WINRT_API
--    return SetFilePointerEx(hFile, pos, newPos, dwMoveMethod);
--#else
--    LONG lHigh = pos.HighPart;
--    DWORD dwNewPos = SetFilePointer(hFile, pos.LowPart, &lHigh, dwMoveMethod);
--    BOOL fOk = TRUE;
--    if (dwNewPos == 0xFFFFFFFF)
--        if (GetLastError() != NO_ERROR)
--            fOk = FALSE;
--    if ((newPos != NULL) && (fOk))
--    {
--        newPos->LowPart = dwNewPos;
--        newPos->HighPart = lHigh;
--    }
--    return fOk;
--#endif
--}
--
--long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream)
--{
--    long ret=-1;
--    HANDLE hFile = NULL;
--    if (stream!=NULL)
--        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
--    if (hFile != NULL)
--    {
--        LARGE_INTEGER pos;
--        pos.QuadPart = 0;
--
--        if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT))
--        {
--            DWORD dwErr = GetLastError();
--            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
--            ret = -1;
--        }
--        else
--            ret=(long)pos.LowPart;
--    }
--    return ret;
--}
--
--ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream)
--{
--    ZPOS64_T ret= (ZPOS64_T)-1;
--    HANDLE hFile = NULL;
--    if (stream!=NULL)
--        hFile = ((WIN32FILE_IOWIN*)stream)->hf;
--
--    if (hFile)
--    {
--        LARGE_INTEGER pos;
--        pos.QuadPart = 0;
--
--        if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT))
--        {
--            DWORD dwErr = GetLastError();
--            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
--            ret = (ZPOS64_T)-1;
--        }
--        else
--            ret=pos.QuadPart;
--    }
--    return ret;
--}
--
--
--long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin)
--{
--    DWORD dwMoveMethod=0xFFFFFFFF;
--    HANDLE hFile = NULL;
--
--    long ret=-1;
--    if (stream!=NULL)
--        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
--    switch (origin)
--    {
--    case ZLIB_FILEFUNC_SEEK_CUR :
--        dwMoveMethod = FILE_CURRENT;
--        break;
--    case ZLIB_FILEFUNC_SEEK_END :
--        dwMoveMethod = FILE_END;
--        break;
--    case ZLIB_FILEFUNC_SEEK_SET :
--        dwMoveMethod = FILE_BEGIN;
--        break;
--    default: return -1;
--    }
--
--    if (hFile != NULL)
--    {
--        LARGE_INTEGER pos;
--        pos.QuadPart = offset;
--        if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod))
--        {
--            DWORD dwErr = GetLastError();
--            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
--            ret = -1;
--        }
--        else
--            ret=0;
--    }
--    return ret;
--}
--
--long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
--{
--    DWORD dwMoveMethod=0xFFFFFFFF;
--    HANDLE hFile = NULL;
--    long ret=-1;
--
--    if (stream!=NULL)
--        hFile = ((WIN32FILE_IOWIN*)stream)->hf;
--
--    switch (origin)
--    {
--        case ZLIB_FILEFUNC_SEEK_CUR :
--            dwMoveMethod = FILE_CURRENT;
--            break;
--        case ZLIB_FILEFUNC_SEEK_END :
--            dwMoveMethod = FILE_END;
--            break;
--        case ZLIB_FILEFUNC_SEEK_SET :
--            dwMoveMethod = FILE_BEGIN;
--            break;
--        default: return -1;
--    }
--
--    if (hFile)
--    {
--        LARGE_INTEGER pos;
--        pos.QuadPart = offset;
--        if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod))
--        {
--            DWORD dwErr = GetLastError();
--            ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
--            ret = -1;
--        }
--        else
--            ret=0;
--    }
--    return ret;
--}
--
--int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream)
--{
--    int ret=-1;
--
--    if (stream!=NULL)
--    {
--        HANDLE hFile;
--        hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
--        if (hFile != NULL)
--        {
--            CloseHandle(hFile);
--            ret=0;
--        }
--        free(stream);
--    }
--    return ret;
--}
--
--int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream)
--{
--    int ret=-1;
--    if (stream!=NULL)
--    {
--        ret = ((WIN32FILE_IOWIN*)stream) -> error;
--    }
--    return ret;
--}
--
--void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
--{
--    pzlib_filefunc_def->zopen_file = win32_open_file_func;
--    pzlib_filefunc_def->zread_file = win32_read_file_func;
--    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
--    pzlib_filefunc_def->ztell_file = win32_tell_file_func;
--    pzlib_filefunc_def->zseek_file = win32_seek_file_func;
--    pzlib_filefunc_def->zclose_file = win32_close_file_func;
--    pzlib_filefunc_def->zerror_file = win32_error_file_func;
--    pzlib_filefunc_def->opaque = NULL;
--}
--
--void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def)
--{
--    pzlib_filefunc_def->zopen64_file = win32_open64_file_func;
--    pzlib_filefunc_def->zread_file = win32_read_file_func;
--    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
--    pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
--    pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
--    pzlib_filefunc_def->zclose_file = win32_close_file_func;
--    pzlib_filefunc_def->zerror_file = win32_error_file_func;
--    pzlib_filefunc_def->opaque = NULL;
--}
--
--
--void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def)
--{
--    pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA;
--    pzlib_filefunc_def->zread_file = win32_read_file_func;
--    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
--    pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
--    pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
--    pzlib_filefunc_def->zclose_file = win32_close_file_func;
--    pzlib_filefunc_def->zerror_file = win32_error_file_func;
--    pzlib_filefunc_def->opaque = NULL;
--}
--
--
--void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def)
--{
--    pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW;
--    pzlib_filefunc_def->zread_file = win32_read_file_func;
--    pzlib_filefunc_def->zwrite_file = win32_write_file_func;
--    pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
--    pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
--    pzlib_filefunc_def->zclose_file = win32_close_file_func;
--    pzlib_filefunc_def->zerror_file = win32_error_file_func;
--    pzlib_filefunc_def->opaque = NULL;
--}
diff --cc zlib/contrib/minizip/iowin32.h
index 0ca0969a7d09a487b1b2b5d74b805837a3bf2e96,0ca0969a7d09a487b1b2b5d74b805837a3bf2e96..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,28 -1,28 +1,0 @@@
--/* iowin32.h -- IO base function header for compress/uncompress .zip
--     Version 1.1, February 14h, 2010
--     part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications for Zip64 support
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--*/
--
--#include <windows.h>
--
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
--void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def));
--void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def));
--void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def));
--
--#ifdef __cplusplus
--}
--#endif
diff --cc zlib/contrib/minizip/make_vms.com
index 9ac13a98fa5fb4769bdd1e818dd1d07d83f79a8b,9ac13a98fa5fb4769bdd1e818dd1d07d83f79a8b..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,25 -1,25 +1,0 @@@
--$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig
--$ open/write zdef vmsdefs.h
--$ copy sys$input: zdef
--$ deck
--#define unix
--#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from
--#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator
--#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord
--#define Write_EndOfCentralDirectoryRecord Write_EoDRecord
--$ eod
--$ close zdef
--$ copy vmsdefs.h,ioapi.h_orig ioapi.h
--$ cc/include=[--]/prefix=all ioapi.c
--$ cc/include=[--]/prefix=all miniunz.c
--$ cc/include=[--]/prefix=all unzip.c
--$ cc/include=[--]/prefix=all minizip.c
--$ cc/include=[--]/prefix=all zip.c
--$ link miniunz,unzip,ioapi,[--]libz.olb/lib
--$ link minizip,zip,ioapi,[--]libz.olb/lib
--$ mcr []minizip test minizip_info.txt
--$ mcr []miniunz -l test.zip
--$ rename minizip_info.txt; minizip_info.txt_old
--$ mcr []miniunz test.zip
--$ delete test.zip;*
--$exit
diff --cc zlib/contrib/minizip/miniunz.c
index 3d65401be5cdd7b58c57d681e28347278942917b,3d65401be5cdd7b58c57d681e28347278942917b..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,660 -1,660 +1,0 @@@
--/*
--   miniunz.c
--   Version 1.1, February 14h, 2010
--   sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications of Unzip for Zip64
--         Copyright (C) 2007-2008 Even Rouault
--
--         Modifications for Zip64 support on both zip and unzip
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--*/
--
--#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
--        #ifndef __USE_FILE_OFFSET64
--                #define __USE_FILE_OFFSET64
--        #endif
--        #ifndef __USE_LARGEFILE64
--                #define __USE_LARGEFILE64
--        #endif
--        #ifndef _LARGEFILE64_SOURCE
--                #define _LARGEFILE64_SOURCE
--        #endif
--        #ifndef _FILE_OFFSET_BIT
--                #define _FILE_OFFSET_BIT 64
--        #endif
--#endif
--
--#ifdef __APPLE__
--// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
--#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
--#define FTELLO_FUNC(stream) ftello(stream)
--#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
--#else
--#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
--#define FTELLO_FUNC(stream) ftello64(stream)
--#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
--#endif
--
--
--#include <stdio.h>
--#include <stdlib.h>
--#include <string.h>
--#include <time.h>
--#include <errno.h>
--#include <fcntl.h>
--
--#ifdef _WIN32
--# include <direct.h>
--# include <io.h>
--#else
--# include <unistd.h>
--# include <utime.h>
--#endif
--
--
--#include "unzip.h"
--
--#define CASESENSITIVITY (0)
--#define WRITEBUFFERSIZE (8192)
--#define MAXFILENAME (256)
--
--#ifdef _WIN32
--#define USEWIN32IOAPI
--#include "iowin32.h"
--#endif
--/*
--  mini unzip, demo of unzip package
--
--  usage :
--  Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
--
--  list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
--    if it exists
--*/
--
--
--/* change_file_date : change the date/time of a file
--    filename : the filename of the file where date/time must be modified
--    dosdate : the new date at the MSDos format (4 bytes)
--    tmu_date : the SAME new date at the tm_unz format */
--void change_file_date(filename,dosdate,tmu_date)
--    const char *filename;
--    uLong dosdate;
--    tm_unz tmu_date;
--{
--#ifdef _WIN32
--  HANDLE hFile;
--  FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
--
--  hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE,
--                      0,NULL,OPEN_EXISTING,0,NULL);
--  GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
--  DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
--  LocalFileTimeToFileTime(&ftLocal,&ftm);
--  SetFileTime(hFile,&ftm,&ftLastAcc,&ftm);
--  CloseHandle(hFile);
--#else
--#ifdef unix || __APPLE__
--  struct utimbuf ut;
--  struct tm newdate;
--  newdate.tm_sec = tmu_date.tm_sec;
--  newdate.tm_min=tmu_date.tm_min;
--  newdate.tm_hour=tmu_date.tm_hour;
--  newdate.tm_mday=tmu_date.tm_mday;
--  newdate.tm_mon=tmu_date.tm_mon;
--  if (tmu_date.tm_year > 1900)
--      newdate.tm_year=tmu_date.tm_year - 1900;
--  else
--      newdate.tm_year=tmu_date.tm_year ;
--  newdate.tm_isdst=-1;
--
--  ut.actime=ut.modtime=mktime(&newdate);
--  utime(filename,&ut);
--#endif
--#endif
--}
--
--
--/* mymkdir and change_file_date are not 100 % portable
--   As I don't know well Unix, I wait feedback for the unix portion */
--
--int mymkdir(dirname)
--    const char* dirname;
--{
--    int ret=0;
--#ifdef _WIN32
--    ret = _mkdir(dirname);
--#elif unix
--    ret = mkdir (dirname,0775);
--#elif __APPLE__
--    ret = mkdir (dirname,0775);
--#endif
--    return ret;
--}
--
--int makedir (newdir)
--    char *newdir;
--{
--  char *buffer ;
--  char *p;
--  int  len = (int)strlen(newdir);
--
--  if (len <= 0)
--    return 0;
--
--  buffer = (char*)malloc(len+1);
--        if (buffer==NULL)
--        {
--                printf("Error allocating memory\n");
--                return UNZ_INTERNALERROR;
--        }
--  strcpy(buffer,newdir);
--
--  if (buffer[len-1] == '/') {
--    buffer[len-1] = '\0';
--  }
--  if (mymkdir(buffer) == 0)
--    {
--      free(buffer);
--      return 1;
--    }
--
--  p = buffer+1;
--  while (1)
--    {
--      char hold;
--
--      while(*p && *p != '\\' && *p != '/')
--        p++;
--      hold = *p;
--      *p = 0;
--      if ((mymkdir(buffer) == -1) && (errno == ENOENT))
--        {
--          printf("couldn't create directory %s\n",buffer);
--          free(buffer);
--          return 0;
--        }
--      if (hold == 0)
--        break;
--      *p++ = hold;
--    }
--  free(buffer);
--  return 1;
--}
--
--void do_banner()
--{
--    printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
--    printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
--}
--
--void do_help()
--{
--    printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
--           "  -e  Extract without pathname (junk paths)\n" \
--           "  -x  Extract with pathname\n" \
--           "  -v  list files\n" \
--           "  -l  list files\n" \
--           "  -d  directory to extract into\n" \
--           "  -o  overwrite files without prompting\n" \
--           "  -p  extract crypted file using password\n\n");
--}
--
--void Display64BitsSize(ZPOS64_T n, int size_char)
--{
--  /* to avoid compatibility problem , we do here the conversion */
--  char number[21];
--  int offset=19;
--  int pos_string = 19;
--  number[20]=0;
--  for (;;) {
--      number[offset]=(char)((n%10)+'0');
--      if (number[offset] != '0')
--          pos_string=offset;
--      n/=10;
--      if (offset==0)
--          break;
--      offset--;
--  }
--  {
--      int size_display_string = 19-pos_string;
--      while (size_char > size_display_string)
--      {
--          size_char--;
--          printf(" ");
--      }
--  }
--
--  printf("%s",&number[pos_string]);
--}
--
--int do_list(uf)
--    unzFile uf;
--{
--    uLong i;
--    unz_global_info64 gi;
--    int err;
--
--    err = unzGetGlobalInfo64(uf,&gi);
--    if (err!=UNZ_OK)
--        printf("error %d with zipfile in unzGetGlobalInfo \n",err);
--    printf("  Length  Method     Size Ratio   Date    Time   CRC-32     Name\n");
--    printf("  ------  ------     ---- -----   ----    ----   ------     ----\n");
--    for (i=0;i<gi.number_entry;i++)
--    {
--        char filename_inzip[256];
--        unz_file_info64 file_info;
--        uLong ratio=0;
--        const char *string_method;
--        char charCrypt=' ';
--        err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
--        if (err!=UNZ_OK)
--        {
--            printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
--            break;
--        }
--        if (file_info.uncompressed_size>0)
--            ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size);
--
--        /* display a '*' if the file is crypted */
--        if ((file_info.flag & 1) != 0)
--            charCrypt='*';
--
--        if (file_info.compression_method==0)
--            string_method="Stored";
--        else
--        if (file_info.compression_method==Z_DEFLATED)
--        {
--            uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
--            if (iLevel==0)
--              string_method="Defl:N";
--            else if (iLevel==1)
--              string_method="Defl:X";
--            else if ((iLevel==2) || (iLevel==3))
--              string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
--        }
--        else
--        if (file_info.compression_method==Z_BZIP2ED)
--        {
--              string_method="BZip2 ";
--        }
--        else
--            string_method="Unkn. ";
--
--        Display64BitsSize(file_info.uncompressed_size,7);
--        printf("  %6s%c",string_method,charCrypt);
--        Display64BitsSize(file_info.compressed_size,7);
--        printf(" %3lu%%  %2.2lu-%2.2lu-%2.2lu  %2.2lu:%2.2lu  %8.8lx   %s\n",
--                ratio,
--                (uLong)file_info.tmu_date.tm_mon + 1,
--                (uLong)file_info.tmu_date.tm_mday,
--                (uLong)file_info.tmu_date.tm_year % 100,
--                (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
--                (uLong)file_info.crc,filename_inzip);
--        if ((i+1)<gi.number_entry)
--        {
--            err = unzGoToNextFile(uf);
--            if (err!=UNZ_OK)
--            {
--                printf("error %d with zipfile in unzGoToNextFile\n",err);
--                break;
--            }
--        }
--    }
--
--    return 0;
--}
--
--
--int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
--    unzFile uf;
--    const int* popt_extract_without_path;
--    int* popt_overwrite;
--    const char* password;
--{
--    char filename_inzip[256];
--    char* filename_withoutpath;
--    char* p;
--    int err=UNZ_OK;
--    FILE *fout=NULL;
--    void* buf;
--    uInt size_buf;
--
--    unz_file_info64 file_info;
--    uLong ratio=0;
--    err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
--
--    if (err!=UNZ_OK)
--    {
--        printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
--        return err;
--    }
--
--    size_buf = WRITEBUFFERSIZE;
--    buf = (void*)malloc(size_buf);
--    if (buf==NULL)
--    {
--        printf("Error allocating memory\n");
--        return UNZ_INTERNALERROR;
--    }
--
--    p = filename_withoutpath = filename_inzip;
--    while ((*p) != '\0')
--    {
--        if (((*p)=='/') || ((*p)=='\\'))
--            filename_withoutpath = p+1;
--        p++;
--    }
--
--    if ((*filename_withoutpath)=='\0')
--    {
--        if ((*popt_extract_without_path)==0)
--        {
--            printf("creating directory: %s\n",filename_inzip);
--            mymkdir(filename_inzip);
--        }
--    }
--    else
--    {
--        const char* write_filename;
--        int skip=0;
--
--        if ((*popt_extract_without_path)==0)
--            write_filename = filename_inzip;
--        else
--            write_filename = filename_withoutpath;
--
--        err = unzOpenCurrentFilePassword(uf,password);
--        if (err!=UNZ_OK)
--        {
--            printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
--        }
--
--        if (((*popt_overwrite)==0) && (err==UNZ_OK))
--        {
--            char rep=0;
--            FILE* ftestexist;
--            ftestexist = FOPEN_FUNC(write_filename,"rb");
--            if (ftestexist!=NULL)
--            {
--                fclose(ftestexist);
--                do
--                {
--                    char answer[128];
--                    int ret;
--
--                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
--                    ret = scanf("%1s",answer);
--                    if (ret != 1)
--                    {
--                       exit(EXIT_FAILURE);
--                    }
--                    rep = answer[0] ;
--                    if ((rep>='a') && (rep<='z'))
--                        rep -= 0x20;
--                }
--                while ((rep!='Y') && (rep!='N') && (rep!='A'));
--            }
--
--            if (rep == 'N')
--                skip = 1;
--
--            if (rep == 'A')
--                *popt_overwrite=1;
--        }
--
--        if ((skip==0) && (err==UNZ_OK))
--        {
--            fout=FOPEN_FUNC(write_filename,"wb");
--            /* some zipfile don't contain directory alone before file */
--            if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
--                                (filename_withoutpath!=(char*)filename_inzip))
--            {
--                char c=*(filename_withoutpath-1);
--                *(filename_withoutpath-1)='\0';
--                makedir(write_filename);
--                *(filename_withoutpath-1)=c;
--                fout=FOPEN_FUNC(write_filename,"wb");
--            }
--
--            if (fout==NULL)
--            {
--                printf("error opening %s\n",write_filename);
--            }
--        }
--
--        if (fout!=NULL)
--        {
--            printf(" extracting: %s\n",write_filename);
--
--            do
--            {
--                err = unzReadCurrentFile(uf,buf,size_buf);
--                if (err<0)
--                {
--                    printf("error %d with zipfile in unzReadCurrentFile\n",err);
--                    break;
--                }
--                if (err>0)
--                    if (fwrite(buf,err,1,fout)!=1)
--                    {
--                        printf("error in writing extracted file\n");
--                        err=UNZ_ERRNO;
--                        break;
--                    }
--            }
--            while (err>0);
--            if (fout)
--                    fclose(fout);
--
--            if (err==0)
--                change_file_date(write_filename,file_info.dosDate,
--                                 file_info.tmu_date);
--        }
--
--        if (err==UNZ_OK)
--        {
--            err = unzCloseCurrentFile (uf);
--            if (err!=UNZ_OK)
--            {
--                printf("error %d with zipfile in unzCloseCurrentFile\n",err);
--            }
--        }
--        else
--            unzCloseCurrentFile(uf); /* don't lose the error */
--    }
--
--    free(buf);
--    return err;
--}
--
--
--int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
--    unzFile uf;
--    int opt_extract_without_path;
--    int opt_overwrite;
--    const char* password;
--{
--    uLong i;
--    unz_global_info64 gi;
--    int err;
--    FILE* fout=NULL;
--
--    err = unzGetGlobalInfo64(uf,&gi);
--    if (err!=UNZ_OK)
--        printf("error %d with zipfile in unzGetGlobalInfo \n",err);
--
--    for (i=0;i<gi.number_entry;i++)
--    {
--        if (do_extract_currentfile(uf,&opt_extract_without_path,
--                                      &opt_overwrite,
--                                      password) != UNZ_OK)
--            break;
--
--        if ((i+1)<gi.number_entry)
--        {
--            err = unzGoToNextFile(uf);
--            if (err!=UNZ_OK)
--            {
--                printf("error %d with zipfile in unzGoToNextFile\n",err);
--                break;
--            }
--        }
--    }
--
--    return 0;
--}
--
--int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)
--    unzFile uf;
--    const char* filename;
--    int opt_extract_without_path;
--    int opt_overwrite;
--    const char* password;
--{
--    int err = UNZ_OK;
--    if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK)
--    {
--        printf("file %s not found in the zipfile\n",filename);
--        return 2;
--    }
--
--    if (do_extract_currentfile(uf,&opt_extract_without_path,
--                                      &opt_overwrite,
--                                      password) == UNZ_OK)
--        return 0;
--    else
--        return 1;
--}
--
--
--int main(argc,argv)
--    int argc;
--    char *argv[];
--{
--    const char *zipfilename=NULL;
--    const char *filename_to_extract=NULL;
--    const char *password=NULL;
--    char filename_try[MAXFILENAME+16] = "";
--    int i;
--    int ret_value=0;
--    int opt_do_list=0;
--    int opt_do_extract=1;
--    int opt_do_extract_withoutpath=0;
--    int opt_overwrite=0;
--    int opt_extractdir=0;
--    const char *dirname=NULL;
--    unzFile uf=NULL;
--
--    do_banner();
--    if (argc==1)
--    {
--        do_help();
--        return 0;
--    }
--    else
--    {
--        for (i=1;i<argc;i++)
--        {
--            if ((*argv[i])=='-')
--            {
--                const char *p=argv[i]+1;
--
--                while ((*p)!='\0')
--                {
--                    char c=*(p++);;
--                    if ((c=='l') || (c=='L'))
--                        opt_do_list = 1;
--                    if ((c=='v') || (c=='V'))
--                        opt_do_list = 1;
--                    if ((c=='x') || (c=='X'))
--                        opt_do_extract = 1;
--                    if ((c=='e') || (c=='E'))
--                        opt_do_extract = opt_do_extract_withoutpath = 1;
--                    if ((c=='o') || (c=='O'))
--                        opt_overwrite=1;
--                    if ((c=='d') || (c=='D'))
--                    {
--                        opt_extractdir=1;
--                        dirname=argv[i+1];
--                    }
--
--                    if (((c=='p') || (c=='P')) && (i+1<argc))
--                    {
--                        password=argv[i+1];
--                        i++;
--                    }
--                }
--            }
--            else
--            {
--                if (zipfilename == NULL)
--                    zipfilename = argv[i];
--                else if ((filename_to_extract==NULL) && (!opt_extractdir))
--                        filename_to_extract = argv[i] ;
--            }
--        }
--    }
--
--    if (zipfilename!=NULL)
--    {
--
--#        ifdef USEWIN32IOAPI
--        zlib_filefunc64_def ffunc;
--#        endif
--
--        strncpy(filename_try, zipfilename,MAXFILENAME-1);
--        /* strncpy doesnt append the trailing NULL, of the string is too long. */
--        filename_try[ MAXFILENAME ] = '\0';
--
--#        ifdef USEWIN32IOAPI
--        fill_win32_filefunc64A(&ffunc);
--        uf = unzOpen2_64(zipfilename,&ffunc);
--#        else
--        uf = unzOpen64(zipfilename);
--#        endif
--        if (uf==NULL)
--        {
--            strcat(filename_try,".zip");
--#            ifdef USEWIN32IOAPI
--            uf = unzOpen2_64(filename_try,&ffunc);
--#            else
--            uf = unzOpen64(filename_try);
--#            endif
--        }
--    }
--
--    if (uf==NULL)
--    {
--        printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
--        return 1;
--    }
--    printf("%s opened\n",filename_try);
--
--    if (opt_do_list==1)
--        ret_value = do_list(uf);
--    else if (opt_do_extract==1)
--    {
--#ifdef _WIN32
--        if (opt_extractdir && _chdir(dirname))
--#else
--        if (opt_extractdir && chdir(dirname))
--#endif
--        {
--          printf("Error changing into %s, aborting\n", dirname);
--          exit(-1);
--        }
--
--        if (filename_to_extract == NULL)
--            ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
--        else
--            ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
--    }
--
--    unzClose(uf);
--
--    return ret_value;
--}
diff --cc zlib/contrib/minizip/miniunzip.1
index 111ac69190f0b2153a6f263f0ce8c888984b527c,111ac69190f0b2153a6f263f0ce8c888984b527c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,63 -1,63 +1,0 @@@
--.\"                                      Hey, EMACS: -*- nroff -*-
--.TH miniunzip 1 "Nov 7, 2001"
--.\" Please adjust this date whenever revising the manpage.
--.\"
--.\" Some roff macros, for reference:
--.\" .nh        disable hyphenation
--.\" .hy        enable hyphenation
--.\" .ad l      left justify
--.\" .ad b      justify to both left and right margins
--.\" .nf        disable filling
--.\" .fi        enable filling
--.\" .br        insert line break
--.\" .sp <n>    insert n+1 empty lines
--.\" for manpage-specific macros, see man(7)
--.SH NAME
--miniunzip - uncompress and examine ZIP archives
--.SH SYNOPSIS
--.B miniunzip
--.RI [ -exvlo ]
--zipfile [ files_to_extract ] [-d tempdir]
--.SH DESCRIPTION
--.B minizip
--is a simple tool which allows the extraction of compressed file
--archives in the ZIP format used by the MS-DOS utility PKZIP.  It was
--written as a demonstration of the
--.IR zlib (3)
--library and therefore lack many of the features of the
--.IR unzip (1)
--program.
--.SH OPTIONS
--A number of options are supported.  With the exception of
--.BI \-d\  tempdir
--these must be supplied before any
--other arguments and are:
--.TP
--.BI \-l\ ,\ \-\-v
--List the files in the archive without extracting them.
--.TP
--.B \-o
--Overwrite files without prompting for confirmation.
--.TP
--.B \-x
--Extract files (default).
--.PP
--The
--.I zipfile
--argument is the name of the archive to process. The next argument can be used
--to specify a single file to extract from the archive.
--
--Lastly, the following option can be specified at the end of the command-line:
--.TP
--.BI \-d\  tempdir
--Extract the archive in the directory
--.I tempdir
--rather than the current directory.
--.SH SEE ALSO
--.BR minizip (1),
--.BR zlib (3),
--.BR unzip (1).
--.SH AUTHOR
--This program was written by Gilles Vollant.  This manual page was
--written by Mark Brown <broonie@sirena.org.uk>. The -d tempdir option
--was added by Dirk Eddelbuettel <edd@debian.org>.
diff --cc zlib/contrib/minizip/minizip.1
index 1154484c1cc15874a95b5d58af1f41e18bfc0407,1154484c1cc15874a95b5d58af1f41e18bfc0407..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,46 -1,46 +1,0 @@@
--.\"                                      Hey, EMACS: -*- nroff -*-
--.TH minizip 1 "May 2, 2001"
--.\" Please adjust this date whenever revising the manpage.
--.\"
--.\" Some roff macros, for reference:
--.\" .nh        disable hyphenation
--.\" .hy        enable hyphenation
--.\" .ad l      left justify
--.\" .ad b      justify to both left and right margins
--.\" .nf        disable filling
--.\" .fi        enable filling
--.\" .br        insert line break
--.\" .sp <n>    insert n+1 empty lines
--.\" for manpage-specific macros, see man(7)
--.SH NAME
--minizip - create ZIP archives
--.SH SYNOPSIS
--.B minizip
--.RI [ -o ]
--zipfile [ " files" ... ]
--.SH DESCRIPTION
--.B minizip
--is a simple tool which allows the creation of compressed file archives
--in the ZIP format used by the MS-DOS utility PKZIP.  It was written as
--a demonstration of the
--.IR zlib (3)
--library and therefore lack many of the features of the
--.IR zip (1)
--program.
--.SH OPTIONS
--The first argument supplied is the name of the ZIP archive to create or
--.RI -o
--in which case it is ignored and the second argument treated as the
--name of the ZIP file.  If the ZIP file already exists it will be
--overwritten.
--.PP
--Subsequent arguments specify a list of files to place in the ZIP
--archive.  If none are specified then an empty archive will be created.
--.SH SEE ALSO
--.BR miniunzip (1),
--.BR zlib (3),
--.BR zip (1).
--.SH AUTHOR
--This program was written by Gilles Vollant.  This manual page was
--written by Mark Brown <broonie@sirena.org.uk>.
--
diff --cc zlib/contrib/minizip/minizip.c
index 4288962ecef05681db4c62bfa13b2f090b9ce6a8,4288962ecef05681db4c62bfa13b2f090b9ce6a8..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,520 -1,520 +1,0 @@@
--/*
--   minizip.c
--   Version 1.1, February 14h, 2010
--   sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications of Unzip for Zip64
--         Copyright (C) 2007-2008 Even Rouault
--
--         Modifications for Zip64 support on both zip and unzip
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--*/
--
--
--#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
--        #ifndef __USE_FILE_OFFSET64
--                #define __USE_FILE_OFFSET64
--        #endif
--        #ifndef __USE_LARGEFILE64
--                #define __USE_LARGEFILE64
--        #endif
--        #ifndef _LARGEFILE64_SOURCE
--                #define _LARGEFILE64_SOURCE
--        #endif
--        #ifndef _FILE_OFFSET_BIT
--                #define _FILE_OFFSET_BIT 64
--        #endif
--#endif
--
--#ifdef __APPLE__
--// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
--#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
--#define FTELLO_FUNC(stream) ftello(stream)
--#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
--#else
--#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
--#define FTELLO_FUNC(stream) ftello64(stream)
--#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
--#endif
--
--
--
--#include <stdio.h>
--#include <stdlib.h>
--#include <string.h>
--#include <time.h>
--#include <errno.h>
--#include <fcntl.h>
--
--#ifdef _WIN32
--# include <direct.h>
--# include <io.h>
--#else
--# include <unistd.h>
--# include <utime.h>
--# include <sys/types.h>
--# include <sys/stat.h>
--#endif
--
--#include "zip.h"
--
--#ifdef _WIN32
--        #define USEWIN32IOAPI
--        #include "iowin32.h"
--#endif
--
--
--
--#define WRITEBUFFERSIZE (16384)
--#define MAXFILENAME (256)
--
--#ifdef _WIN32
--uLong filetime(f, tmzip, dt)
--    char *f;                /* name of file to get info on */
--    tm_zip *tmzip;             /* return value: access, modific. and creation times */
--    uLong *dt;             /* dostime */
--{
--  int ret = 0;
--  {
--      FILETIME ftLocal;
--      HANDLE hFind;
--      WIN32_FIND_DATAA ff32;
--
--      hFind = FindFirstFileA(f,&ff32);
--      if (hFind != INVALID_HANDLE_VALUE)
--      {
--        FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
--        FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
--        FindClose(hFind);
--        ret = 1;
--      }
--  }
--  return ret;
--}
--#else
--#ifdef unix || __APPLE__
--uLong filetime(f, tmzip, dt)
--    char *f;               /* name of file to get info on */
--    tm_zip *tmzip;         /* return value: access, modific. and creation times */
--    uLong *dt;             /* dostime */
--{
--  int ret=0;
--  struct stat s;        /* results of stat() */
--  struct tm* filedate;
--  time_t tm_t=0;
--
--  if (strcmp(f,"-")!=0)
--  {
--    char name[MAXFILENAME+1];
--    int len = strlen(f);
--    if (len > MAXFILENAME)
--      len = MAXFILENAME;
--
--    strncpy(name, f,MAXFILENAME-1);
--    /* strncpy doesnt append the trailing NULL, of the string is too long. */
--    name[ MAXFILENAME ] = '\0';
--
--    if (name[len - 1] == '/')
--      name[len - 1] = '\0';
--    /* not all systems allow stat'ing a file with / appended */
--    if (stat(name,&s)==0)
--    {
--      tm_t = s.st_mtime;
--      ret = 1;
--    }
--  }
--  filedate = localtime(&tm_t);
--
--  tmzip->tm_sec  = filedate->tm_sec;
--  tmzip->tm_min  = filedate->tm_min;
--  tmzip->tm_hour = filedate->tm_hour;
--  tmzip->tm_mday = filedate->tm_mday;
--  tmzip->tm_mon  = filedate->tm_mon ;
--  tmzip->tm_year = filedate->tm_year;
--
--  return ret;
--}
--#else
--uLong filetime(f, tmzip, dt)
--    char *f;                /* name of file to get info on */
--    tm_zip *tmzip;             /* return value: access, modific. and creation times */
--    uLong *dt;             /* dostime */
--{
--    return 0;
--}
--#endif
--#endif
--
--
--
--
--int check_exist_file(filename)
--    const char* filename;
--{
--    FILE* ftestexist;
--    int ret = 1;
--    ftestexist = FOPEN_FUNC(filename,"rb");
--    if (ftestexist==NULL)
--        ret = 0;
--    else
--        fclose(ftestexist);
--    return ret;
--}
--
--void do_banner()
--{
--    printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
--    printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
--}
--
--void do_help()
--{
--    printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
--           "  -o  Overwrite existing file.zip\n" \
--           "  -a  Append to existing file.zip\n" \
--           "  -0  Store only\n" \
--           "  -1  Compress faster\n" \
--           "  -9  Compress better\n\n" \
--           "  -j  exclude path. store only the file name.\n\n");
--}
--
--/* calculate the CRC32 of a file,
--   because to encrypt a file, we need known the CRC32 of the file before */
--int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc)
--{
--   unsigned long calculate_crc=0;
--   int err=ZIP_OK;
--   FILE * fin = FOPEN_FUNC(filenameinzip,"rb");
--
--   unsigned long size_read = 0;
--   unsigned long total_read = 0;
--   if (fin==NULL)
--   {
--       err = ZIP_ERRNO;
--   }
--
--    if (err == ZIP_OK)
--        do
--        {
--            err = ZIP_OK;
--            size_read = (int)fread(buf,1,size_buf,fin);
--            if (size_read < size_buf)
--                if (feof(fin)==0)
--            {
--                printf("error in reading %s\n",filenameinzip);
--                err = ZIP_ERRNO;
--            }
--
--            if (size_read>0)
--                calculate_crc = crc32(calculate_crc,buf,size_read);
--            total_read += size_read;
--
--        } while ((err == ZIP_OK) && (size_read>0));
--
--    if (fin)
--        fclose(fin);
--
--    *result_crc=calculate_crc;
--    printf("file %s crc %lx\n", filenameinzip, calculate_crc);
--    return err;
--}
--
--int isLargeFile(const char* filename)
--{
--  int largeFile = 0;
--  ZPOS64_T pos = 0;
--  FILE* pFile = FOPEN_FUNC(filename, "rb");
--
--  if(pFile != NULL)
--  {
--    int n = FSEEKO_FUNC(pFile, 0, SEEK_END);
--    pos = FTELLO_FUNC(pFile);
--
--                printf("File : %s is %lld bytes\n", filename, pos);
--
--    if(pos >= 0xffffffff)
--     largeFile = 1;
--
--                fclose(pFile);
--  }
--
-- return largeFile;
--}
--
--int main(argc,argv)
--    int argc;
--    char *argv[];
--{
--    int i;
--    int opt_overwrite=0;
--    int opt_compress_level=Z_DEFAULT_COMPRESSION;
--    int opt_exclude_path=0;
--    int zipfilenamearg = 0;
--    char filename_try[MAXFILENAME+16];
--    int zipok;
--    int err=0;
--    int size_buf=0;
--    void* buf=NULL;
--    const char* password=NULL;
--
--
--    do_banner();
--    if (argc==1)
--    {
--        do_help();
--        return 0;
--    }
--    else
--    {
--        for (i=1;i<argc;i++)
--        {
--            if ((*argv[i])=='-')
--            {
--                const char *p=argv[i]+1;
--
--                while ((*p)!='\0')
--                {
--                    char c=*(p++);;
--                    if ((c=='o') || (c=='O'))
--                        opt_overwrite = 1;
--                    if ((c=='a') || (c=='A'))
--                        opt_overwrite = 2;
--                    if ((c>='0') && (c<='9'))
--                        opt_compress_level = c-'0';
--                    if ((c=='j') || (c=='J'))
--                        opt_exclude_path = 1;
--
--                    if (((c=='p') || (c=='P')) && (i+1<argc))
--                    {
--                        password=argv[i+1];
--                        i++;
--                    }
--                }
--            }
--            else
--            {
--                if (zipfilenamearg == 0)
--                {
--                    zipfilenamearg = i ;
--                }
--            }
--        }
--    }
--
--    size_buf = WRITEBUFFERSIZE;
--    buf = (void*)malloc(size_buf);
--    if (buf==NULL)
--    {
--        printf("Error allocating memory\n");
--        return ZIP_INTERNALERROR;
--    }
--
--    if (zipfilenamearg==0)
--    {
--        zipok=0;
--    }
--    else
--    {
--        int i,len;
--        int dot_found=0;
--
--        zipok = 1 ;
--        strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
--        /* strncpy doesnt append the trailing NULL, of the string is too long. */
--        filename_try[ MAXFILENAME ] = '\0';
--
--        len=(int)strlen(filename_try);
--        for (i=0;i<len;i++)
--            if (filename_try[i]=='.')
--                dot_found=1;
--
--        if (dot_found==0)
--            strcat(filename_try,".zip");
--
--        if (opt_overwrite==2)
--        {
--            /* if the file don't exist, we not append file */
--            if (check_exist_file(filename_try)==0)
--                opt_overwrite=1;
--        }
--        else
--        if (opt_overwrite==0)
--            if (check_exist_file(filename_try)!=0)
--            {
--                char rep=0;
--                do
--                {
--                    char answer[128];
--                    int ret;
--                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
--                    ret = scanf("%1s",answer);
--                    if (ret != 1)
--                    {
--                       exit(EXIT_FAILURE);
--                    }
--                    rep = answer[0] ;
--                    if ((rep>='a') && (rep<='z'))
--                        rep -= 0x20;
--                }
--                while ((rep!='Y') && (rep!='N') && (rep!='A'));
--                if (rep=='N')
--                    zipok = 0;
--                if (rep=='A')
--                    opt_overwrite = 2;
--            }
--    }
--
--    if (zipok==1)
--    {
--        zipFile zf;
--        int errclose;
--#        ifdef USEWIN32IOAPI
--        zlib_filefunc64_def ffunc;
--        fill_win32_filefunc64A(&ffunc);
--        zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
--#        else
--        zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
--#        endif
--
--        if (zf == NULL)
--        {
--            printf("error opening %s\n",filename_try);
--            err= ZIP_ERRNO;
--        }
--        else
--            printf("creating %s\n",filename_try);
--
--        for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
--        {
--            if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
--                  ((argv[i][1]=='o') || (argv[i][1]=='O') ||
--                   (argv[i][1]=='a') || (argv[i][1]=='A') ||
--                   (argv[i][1]=='p') || (argv[i][1]=='P') ||
--                   ((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
--                  (strlen(argv[i]) == 2)))
--            {
--                FILE * fin;
--                int size_read;
--                const char* filenameinzip = argv[i];
--                const char *savefilenameinzip;
--                zip_fileinfo zi;
--                unsigned long crcFile=0;
--                int zip64 = 0;
--
--                zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
--                zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
--                zi.dosDate = 0;
--                zi.internal_fa = 0;
--                zi.external_fa = 0;
--                filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);
--
--/*
--                err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
--                                 NULL,0,NULL,0,NULL / * comment * /,
--                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
--                                 opt_compress_level);
--*/
--                if ((password != NULL) && (err==ZIP_OK))
--                    err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
--
--                zip64 = isLargeFile(filenameinzip);
--
--                                                         /* The path name saved, should not include a leading slash. */
--               /*if it did, windows/xp and dynazip couldn't read the zip file. */
--                 savefilenameinzip = filenameinzip;
--                 while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
--                 {
--                     savefilenameinzip++;
--                 }
--
--                 /*should the zip file contain any path at all?*/
--                 if( opt_exclude_path )
--                 {
--                     const char *tmpptr;
--                     const char *lastslash = 0;
--                     for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
--                     {
--                         if( *tmpptr == '\\' || *tmpptr == '/')
--                         {
--                             lastslash = tmpptr;
--                         }
--                     }
--                     if( lastslash != NULL )
--                     {
--                         savefilenameinzip = lastslash+1; // base filename follows last slash.
--                     }
--                 }
--
--                 /**/
--                err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
--                                 NULL,0,NULL,0,NULL /* comment*/,
--                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
--                                 opt_compress_level,0,
--                                 /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
--                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
--                                 password,crcFile, zip64);
--
--                if (err != ZIP_OK)
--                    printf("error in opening %s in zipfile\n",filenameinzip);
--                else
--                {
--                    fin = FOPEN_FUNC(filenameinzip,"rb");
--                    if (fin==NULL)
--                    {
--                        err=ZIP_ERRNO;
--                        printf("error in opening %s for reading\n",filenameinzip);
--                    }
--                }
--
--                if (err == ZIP_OK)
--                    do
--                    {
--                        err = ZIP_OK;
--                        size_read = (int)fread(buf,1,size_buf,fin);
--                        if (size_read < size_buf)
--                            if (feof(fin)==0)
--                        {
--                            printf("error in reading %s\n",filenameinzip);
--                            err = ZIP_ERRNO;
--                        }
--
--                        if (size_read>0)
--                        {
--                            err = zipWriteInFileInZip (zf,buf,size_read);
--                            if (err<0)
--                            {
--                                printf("error in writing %s in the zipfile\n",
--                                                 filenameinzip);
--                            }
--
--                        }
--                    } while ((err == ZIP_OK) && (size_read>0));
--
--                if (fin)
--                    fclose(fin);
--
--                if (err<0)
--                    err=ZIP_ERRNO;
--                else
--                {
--                    err = zipCloseFileInZip(zf);
--                    if (err!=ZIP_OK)
--                        printf("error in closing %s in the zipfile\n",
--                                    filenameinzip);
--                }
--            }
--        }
--        errclose = zipClose(zf,NULL);
--        if (errclose != ZIP_OK)
--            printf("error in closing %s\n",filename_try);
--    }
--    else
--    {
--       do_help();
--    }
--
--    free(buf);
--    return 0;
--}
diff --cc zlib/contrib/minizip/minizip.pc.in
index 69b5b7fdcb3b4ae67ac7f9ee23733a59dac7e665,69b5b7fdcb3b4ae67ac7f9ee23733a59dac7e665..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,12 -1,12 +1,0 @@@
--prefix=@prefix@
--exec_prefix=@exec_prefix@
--libdir=@libdir@
--includedir=@includedir@/minizip
--
--Name: minizip
--Description: Minizip zip file manipulation library
--Requires:
--Version: @PACKAGE_VERSION@
--Libs: -L${libdir} -lminizip
--Libs.private: -lz
--Cflags: -I${includedir}
diff --cc zlib/contrib/minizip/mztools.c
index 96891c2e0b71ef95a50a0c3271c83e5a2123d025,96891c2e0b71ef95a50a0c3271c83e5a2123d025..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,291 -1,291 +1,0 @@@
--/*
--  Additional tools for Minizip
--  Code: Xavier Roche '2004
--  License: Same as ZLIB (www.gzip.org)
--*/
--
--/* Code */
--#include <stdio.h>
--#include <stdlib.h>
--#include <string.h>
--#include "zlib.h"
--#include "unzip.h"
--
--#define READ_8(adr)  ((unsigned char)*(adr))
--#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) )
--#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) )
--
--#define WRITE_8(buff, n) do { \
--  *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \
--} while(0)
--#define WRITE_16(buff, n) do { \
--  WRITE_8((unsigned char*)(buff), n); \
--  WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \
--} while(0)
--#define WRITE_32(buff, n) do { \
--  WRITE_16((unsigned char*)(buff), (n) & 0xffff); \
--  WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \
--} while(0)
--
--extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered)
--const char* file;
--const char* fileOut;
--const char* fileOutTmp;
--uLong* nRecovered;
--uLong* bytesRecovered;
--{
--  int err = Z_OK;
--  FILE* fpZip = fopen(file, "rb");
--  FILE* fpOut = fopen(fileOut, "wb");
--  FILE* fpOutCD = fopen(fileOutTmp, "wb");
--  if (fpZip != NULL &&  fpOut != NULL) {
--    int entries = 0;
--    uLong totalBytes = 0;
--    char header[30];
--    char filename[1024];
--    char extra[1024];
--    int offset = 0;
--    int offsetCD = 0;
--    while ( fread(header, 1, 30, fpZip) == 30 ) {
--      int currentOffset = offset;
--
--      /* File entry */
--      if (READ_32(header) == 0x04034b50) {
--        unsigned int version = READ_16(header + 4);
--        unsigned int gpflag = READ_16(header + 6);
--        unsigned int method = READ_16(header + 8);
--        unsigned int filetime = READ_16(header + 10);
--        unsigned int filedate = READ_16(header + 12);
--        unsigned int crc = READ_32(header + 14); /* crc */
--        unsigned int cpsize = READ_32(header + 18); /* compressed size */
--        unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */
--        unsigned int fnsize = READ_16(header + 26); /* file name length */
--        unsigned int extsize = READ_16(header + 28); /* extra field length */
--        filename[0] = extra[0] = '\0';
--
--        /* Header */
--        if (fwrite(header, 1, 30, fpOut) == 30) {
--          offset += 30;
--        } else {
--          err = Z_ERRNO;
--          break;
--        }
--
--        /* Filename */
--        if (fnsize > 0) {
--          if (fnsize < sizeof(filename)) {
--            if (fread(filename, 1, fnsize, fpZip) == fnsize) {
--                if (fwrite(filename, 1, fnsize, fpOut) == fnsize) {
--                offset += fnsize;
--              } else {
--                err = Z_ERRNO;
--                break;
--              }
--            } else {
--              err = Z_ERRNO;
--              break;
--            }
--          } else {
--            err = Z_ERRNO;
--            break;
--          }
--        } else {
--          err = Z_STREAM_ERROR;
--          break;
--        }
--
--        /* Extra field */
--        if (extsize > 0) {
--          if (extsize < sizeof(extra)) {
--            if (fread(extra, 1, extsize, fpZip) == extsize) {
--              if (fwrite(extra, 1, extsize, fpOut) == extsize) {
--                offset += extsize;
--                } else {
--                err = Z_ERRNO;
--                break;
--              }
--            } else {
--              err = Z_ERRNO;
--              break;
--            }
--          } else {
--            err = Z_ERRNO;
--            break;
--          }
--        }
--
--        /* Data */
--        {
--          int dataSize = cpsize;
--          if (dataSize == 0) {
--            dataSize = uncpsize;
--          }
--          if (dataSize > 0) {
--            char* data = malloc(dataSize);
--            if (data != NULL) {
--              if ((int)fread(data, 1, dataSize, fpZip) == dataSize) {
--                if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) {
--                  offset += dataSize;
--                  totalBytes += dataSize;
--                } else {
--                  err = Z_ERRNO;
--                }
--              } else {
--                err = Z_ERRNO;
--              }
--              free(data);
--              if (err != Z_OK) {
--                break;
--              }
--            } else {
--              err = Z_MEM_ERROR;
--              break;
--            }
--          }
--        }
--
--        /* Central directory entry */
--        {
--          char header[46];
--          char* comment = "";
--          int comsize = (int) strlen(comment);
--          WRITE_32(header, 0x02014b50);
--          WRITE_16(header + 4, version);
--          WRITE_16(header + 6, version);
--          WRITE_16(header + 8, gpflag);
--          WRITE_16(header + 10, method);
--          WRITE_16(header + 12, filetime);
--          WRITE_16(header + 14, filedate);
--          WRITE_32(header + 16, crc);
--          WRITE_32(header + 20, cpsize);
--          WRITE_32(header + 24, uncpsize);
--          WRITE_16(header + 28, fnsize);
--          WRITE_16(header + 30, extsize);
--          WRITE_16(header + 32, comsize);
--          WRITE_16(header + 34, 0);     /* disk # */
--          WRITE_16(header + 36, 0);     /* int attrb */
--          WRITE_32(header + 38, 0);     /* ext attrb */
--          WRITE_32(header + 42, currentOffset);
--          /* Header */
--          if (fwrite(header, 1, 46, fpOutCD) == 46) {
--            offsetCD += 46;
--
--            /* Filename */
--            if (fnsize > 0) {
--              if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) {
--                offsetCD += fnsize;
--              } else {
--                err = Z_ERRNO;
--                break;
--              }
--            } else {
--              err = Z_STREAM_ERROR;
--              break;
--            }
--
--            /* Extra field */
--            if (extsize > 0) {
--              if (fwrite(extra, 1, extsize, fpOutCD) == extsize) {
--                offsetCD += extsize;
--              } else {
--                err = Z_ERRNO;
--                break;
--              }
--            }
--
--            /* Comment field */
--            if (comsize > 0) {
--              if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) {
--                offsetCD += comsize;
--              } else {
--                err = Z_ERRNO;
--                break;
--              }
--            }
--
--
--          } else {
--            err = Z_ERRNO;
--            break;
--          }
--        }
--
--        /* Success */
--        entries++;
--
--      } else {
--        break;
--      }
--    }
--
--    /* Final central directory  */
--    {
--      int entriesZip = entries;
--      char header[22];
--      char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools";
--      int comsize = (int) strlen(comment);
--      if (entriesZip > 0xffff) {
--        entriesZip = 0xffff;
--      }
--      WRITE_32(header, 0x06054b50);
--      WRITE_16(header + 4, 0);    /* disk # */
--      WRITE_16(header + 6, 0);    /* disk # */
--      WRITE_16(header + 8, entriesZip);   /* hack */
--      WRITE_16(header + 10, entriesZip);  /* hack */
--      WRITE_32(header + 12, offsetCD);    /* size of CD */
--      WRITE_32(header + 16, offset);      /* offset to CD */
--      WRITE_16(header + 20, comsize);     /* comment */
--
--      /* Header */
--      if (fwrite(header, 1, 22, fpOutCD) == 22) {
--
--        /* Comment field */
--        if (comsize > 0) {
--          if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) {
--            err = Z_ERRNO;
--          }
--        }
--
--      } else {
--        err = Z_ERRNO;
--      }
--    }
--
--    /* Final merge (file + central directory) */
--    fclose(fpOutCD);
--    if (err == Z_OK) {
--      fpOutCD = fopen(fileOutTmp, "rb");
--      if (fpOutCD != NULL) {
--        int nRead;
--        char buffer[8192];
--        while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) {
--          if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) {
--            err = Z_ERRNO;
--            break;
--          }
--        }
--        fclose(fpOutCD);
--      }
--    }
--
--    /* Close */
--    fclose(fpZip);
--    fclose(fpOut);
--
--    /* Wipe temporary file */
--    (void)remove(fileOutTmp);
--
--    /* Number of recovered entries */
--    if (err == Z_OK) {
--      if (nRecovered != NULL) {
--        *nRecovered = entries;
--      }
--      if (bytesRecovered != NULL) {
--        *bytesRecovered = totalBytes;
--      }
--    }
--  } else {
--    err = Z_STREAM_ERROR;
--  }
--  return err;
--}
diff --cc zlib/contrib/minizip/mztools.h
index a49a426ec2fcb279995806adbfd2ed48e781f616,a49a426ec2fcb279995806adbfd2ed48e781f616..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,37 -1,37 +1,0 @@@
--/*
--  Additional tools for Minizip
--  Code: Xavier Roche '2004
--  License: Same as ZLIB (www.gzip.org)
--*/
--
--#ifndef _zip_tools_H
--#define _zip_tools_H
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--#ifndef _ZLIB_H
--#include "zlib.h"
--#endif
--
--#include "unzip.h"
--
--/* Repair a ZIP file (missing central directory)
--   file: file to recover
--   fileOut: output file after recovery
--   fileOutTmp: temporary file name used for recovery
--*/
--extern int ZEXPORT unzRepair(const char* file,
--                             const char* fileOut,
--                             const char* fileOutTmp,
--                             uLong* nRecovered,
--                             uLong* bytesRecovered);
--
--
--#ifdef __cplusplus
--}
--#endif
--
--
--#endif
diff --cc zlib/contrib/minizip/unzip.c
index bcfb9416ec356d1016f890b085677e412ba6e9bf,bcfb9416ec356d1016f890b085677e412ba6e9bf..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2125 -1,2125 +1,0 @@@
--/* unzip.c -- IO for uncompress .zip files using zlib
--   Version 1.1, February 14h, 2010
--   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications of Unzip for Zip64
--         Copyright (C) 2007-2008 Even Rouault
--
--         Modifications for Zip64 support on both zip and unzip
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--
--  ------------------------------------------------------------------------------------
--  Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of
--  compatibility with older software. The following is from the original crypt.c.
--  Code woven in by Terry Thorsen 1/2003.
--
--  Copyright (c) 1990-2000 Info-ZIP.  All rights reserved.
--
--  See the accompanying file LICENSE, version 2000-Apr-09 or later
--  (the contents of which are also included in zip.h) for terms of use.
--  If, for some reason, all these files are missing, the Info-ZIP license
--  also may be found at:  ftp://ftp.info-zip.org/pub/infozip/license.html
--
--        crypt.c (full version) by Info-ZIP.      Last revised:  [see crypt.h]
--
--  The encryption/decryption parts of this source code (as opposed to the
--  non-echoing password parts) were originally written in Europe.  The
--  whole source package can be freely distributed, including from the USA.
--  (Prior to January 2000, re-export from the US was a violation of US law.)
--
--        This encryption code is a direct transcription of the algorithm from
--  Roger Schlafly, described by Phil Katz in the file appnote.txt.  This
--  file (appnote.txt) is distributed with the PKZIP program (even in the
--  version without encryption capabilities).
--
--        ------------------------------------------------------------------------------------
--
--        Changes in unzip.c
--
--        2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos
--  2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz*
--  2007-2008 - Even Rouault - Remove old C style function prototypes
--  2007-2008 - Even Rouault - Add unzip support for ZIP64
--
--        Copyright (C) 2007-2008 Even Rouault
--
--
--        Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again).
--  Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G
--                                should only read the compressed/uncompressed size from the Zip64 format if
--                                the size from normal header was 0xFFFFFFFF
--  Oct-2009 - Mathias Svensson - Applied some bug fixes from paches recived from Gilles Vollant
--        Oct-2009 - Mathias Svensson - Applied support to unzip files with compression mathod BZIP2 (bzip2 lib is required)
--                                Patch created by Daniel Borca
--
--  Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer
--
--  Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson
--
--*/
--
--
--#include <stdio.h>
--#include <stdlib.h>
--#include <string.h>
--
--#ifndef NOUNCRYPT
--        #define NOUNCRYPT
--#endif
--
--#include "zlib.h"
--#include "unzip.h"
--
--#ifdef STDC
--#  include <stddef.h>
--#  include <string.h>
--#  include <stdlib.h>
--#endif
--#ifdef NO_ERRNO_H
--    extern int errno;
--#else
--#   include <errno.h>
--#endif
--
--
--#ifndef local
--#  define local static
--#endif
--/* compile with -Dlocal if your debugger can't find static symbols */
--
--
--#ifndef CASESENSITIVITYDEFAULT_NO
--#  if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES)
--#    define CASESENSITIVITYDEFAULT_NO
--#  endif
--#endif
--
--
--#ifndef UNZ_BUFSIZE
--#define UNZ_BUFSIZE (16384)
--#endif
--
--#ifndef UNZ_MAXFILENAMEINZIP
--#define UNZ_MAXFILENAMEINZIP (256)
--#endif
--
--#ifndef ALLOC
--# define ALLOC(size) (malloc(size))
--#endif
--#ifndef TRYFREE
--# define TRYFREE(p) {if (p) free(p);}
--#endif
--
--#define SIZECENTRALDIRITEM (0x2e)
--#define SIZEZIPLOCALHEADER (0x1e)
--
--
--const char unz_copyright[] =
--   " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
--
--/* unz_file_info_interntal contain internal info about a file in zipfile*/
--typedef struct unz_file_info64_internal_s
--{
--    ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */
--} unz_file_info64_internal;
--
--
--/* file_in_zip_read_info_s contain internal information about a file in zipfile,
--    when reading and decompress it */
--typedef struct
--{
--    char  *read_buffer;         /* internal buffer for compressed data */
--    z_stream stream;            /* zLib stream structure for inflate */
--
--#ifdef HAVE_BZIP2
--    bz_stream bstream;          /* bzLib stream structure for bziped */
--#endif
--
--    ZPOS64_T pos_in_zipfile;       /* position in byte on the zipfile, for fseek*/
--    uLong stream_initialised;   /* flag set if stream structure is initialised*/
--
--    ZPOS64_T offset_local_extrafield;/* offset of the local extra field */
--    uInt  size_local_extrafield;/* size of the local extra field */
--    ZPOS64_T pos_local_extrafield;   /* position in the local extra field in read*/
--    ZPOS64_T total_out_64;
--
--    uLong crc32;                /* crc32 of all data uncompressed */
--    uLong crc32_wait;           /* crc32 we must obtain after decompress all */
--    ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */
--    ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/
--    zlib_filefunc64_32_def z_filefunc;
--    voidpf filestream;        /* io structore of the zipfile */
--    uLong compression_method;   /* compression method (0==store) */
--    ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
--    int   raw;
--} file_in_zip64_read_info_s;
--
--
--/* unz64_s contain internal information about the zipfile
--*/
--typedef struct
--{
--    zlib_filefunc64_32_def z_filefunc;
--    int is64bitOpenFunction;
--    voidpf filestream;        /* io structore of the zipfile */
--    unz_global_info64 gi;       /* public global information */
--    ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
--    ZPOS64_T num_file;             /* number of the current file in the zipfile*/
--    ZPOS64_T pos_in_central_dir;   /* pos of the current file in the central dir*/
--    ZPOS64_T current_file_ok;      /* flag about the usability of the current file*/
--    ZPOS64_T central_pos;          /* position of the beginning of the central dir*/
--
--    ZPOS64_T size_central_dir;     /* size of the central directory  */
--    ZPOS64_T offset_central_dir;   /* offset of start of central directory with
--                                   respect to the starting disk number */
--
--    unz_file_info64 cur_file_info; /* public info about the current file in zip*/
--    unz_file_info64_internal cur_file_info_internal; /* private info about it*/
--    file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current
--                                        file if we are decompressing it */
--    int encrypted;
--
--    int isZip64;
--
--#    ifndef NOUNCRYPT
--    unsigned long keys[3];     /* keys defining the pseudo-random sequence */
--    const z_crc_t* pcrc_32_tab;
--#    endif
--} unz64_s;
--
--
--#ifndef NOUNCRYPT
--#include "crypt.h"
--#endif
--
--/* ===========================================================================
--     Read a byte from a gz_stream; update next_in and avail_in. Return EOF
--   for end of file.
--   IN assertion: the stream s has been successfully opened for reading.
--*/
--
--
--local int unz64local_getByte OF((
--    const zlib_filefunc64_32_def* pzlib_filefunc_def,
--    voidpf filestream,
--    int *pi));
--
--local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi)
--{
--    unsigned char c;
--    int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1);
--    if (err==1)
--    {
--        *pi = (int)c;
--        return UNZ_OK;
--    }
--    else
--    {
--        if (ZERROR64(*pzlib_filefunc_def,filestream))
--            return UNZ_ERRNO;
--        else
--            return UNZ_EOF;
--    }
--}
--
--
--/* ===========================================================================
--   Reads a long in LSB order from the given gz_stream. Sets
--*/
--local int unz64local_getShort OF((
--    const zlib_filefunc64_32_def* pzlib_filefunc_def,
--    voidpf filestream,
--    uLong *pX));
--
--local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def,
--                             voidpf filestream,
--                             uLong *pX)
--{
--    uLong x ;
--    int i = 0;
--    int err;
--
--    err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x = (uLong)i;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((uLong)i)<<8;
--
--    if (err==UNZ_OK)
--        *pX = x;
--    else
--        *pX = 0;
--    return err;
--}
--
--local int unz64local_getLong OF((
--    const zlib_filefunc64_32_def* pzlib_filefunc_def,
--    voidpf filestream,
--    uLong *pX));
--
--local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def,
--                            voidpf filestream,
--                            uLong *pX)
--{
--    uLong x ;
--    int i = 0;
--    int err;
--
--    err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x = (uLong)i;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((uLong)i)<<8;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((uLong)i)<<16;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x += ((uLong)i)<<24;
--
--    if (err==UNZ_OK)
--        *pX = x;
--    else
--        *pX = 0;
--    return err;
--}
--
--local int unz64local_getLong64 OF((
--    const zlib_filefunc64_32_def* pzlib_filefunc_def,
--    voidpf filestream,
--    ZPOS64_T *pX));
--
--
--local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def,
--                            voidpf filestream,
--                            ZPOS64_T *pX)
--{
--    ZPOS64_T x ;
--    int i = 0;
--    int err;
--
--    err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x = (ZPOS64_T)i;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<8;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<16;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<24;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<32;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<40;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<48;
--
--    if (err==UNZ_OK)
--        err = unz64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x |= ((ZPOS64_T)i)<<56;
--
--    if (err==UNZ_OK)
--        *pX = x;
--    else
--        *pX = 0;
--    return err;
--}
--
--/* My own strcmpi / strcasecmp */
--local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2)
--{
--    for (;;)
--    {
--        char c1=*(fileName1++);
--        char c2=*(fileName2++);
--        if ((c1>='a') && (c1<='z'))
--            c1 -= 0x20;
--        if ((c2>='a') && (c2<='z'))
--            c2 -= 0x20;
--        if (c1=='\0')
--            return ((c2=='\0') ? 0 : -1);
--        if (c2=='\0')
--            return 1;
--        if (c1<c2)
--            return -1;
--        if (c1>c2)
--            return 1;
--    }
--}
--
--
--#ifdef  CASESENSITIVITYDEFAULT_NO
--#define CASESENSITIVITYDEFAULTVALUE 2
--#else
--#define CASESENSITIVITYDEFAULTVALUE 1
--#endif
--
--#ifndef STRCMPCASENOSENTIVEFUNCTION
--#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
--#endif
--
--/*
--   Compare two filename (fileName1,fileName2).
--   If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
--   If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
--                                                                or strcasecmp)
--   If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
--        (like 1 on Unix, 2 on Windows)
--
--*/
--extern int ZEXPORT unzStringFileNameCompare (const char*  fileName1,
--                                                 const char*  fileName2,
--                                                 int iCaseSensitivity)
--
--{
--    if (iCaseSensitivity==0)
--        iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
--
--    if (iCaseSensitivity==1)
--        return strcmp(fileName1,fileName2);
--
--    return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
--}
--
--#ifndef BUFREADCOMMENT
--#define BUFREADCOMMENT (0x400)
--#endif
--
--/*
--  Locate the Central directory of a zipfile (at the end, just before
--    the global comment)
--*/
--local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
--local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
--{
--    unsigned char* buf;
--    ZPOS64_T uSizeFile;
--    ZPOS64_T uBackRead;
--    ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
--    ZPOS64_T uPosFound=0;
--
--    if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
--        return 0;
--
--
--    uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
--
--    if (uMaxBack>uSizeFile)
--        uMaxBack = uSizeFile;
--
--    buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
--    if (buf==NULL)
--        return 0;
--
--    uBackRead = 4;
--    while (uBackRead<uMaxBack)
--    {
--        uLong uReadSize;
--        ZPOS64_T uReadPos ;
--        int i;
--        if (uBackRead+BUFREADCOMMENT>uMaxBack)
--            uBackRead = uMaxBack;
--        else
--            uBackRead+=BUFREADCOMMENT;
--        uReadPos = uSizeFile-uBackRead ;
--
--        uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
--                     (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
--        if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--            break;
--
--        if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
--            break;
--
--        for (i=(int)uReadSize-3; (i--)>0;)
--            if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
--                ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
--            {
--                uPosFound = uReadPos+i;
--                break;
--            }
--
--        if (uPosFound!=0)
--            break;
--    }
--    TRYFREE(buf);
--    return uPosFound;
--}
--
--
--/*
--  Locate the Central directory 64 of a zipfile (at the end, just before
--    the global comment)
--*/
--local ZPOS64_T unz64local_SearchCentralDir64 OF((
--    const zlib_filefunc64_32_def* pzlib_filefunc_def,
--    voidpf filestream));
--
--local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def,
--                                      voidpf filestream)
--{
--    unsigned char* buf;
--    ZPOS64_T uSizeFile;
--    ZPOS64_T uBackRead;
--    ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
--    ZPOS64_T uPosFound=0;
--    uLong uL;
--                ZPOS64_T relativeOffset;
--
--    if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
--        return 0;
--
--
--    uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
--
--    if (uMaxBack>uSizeFile)
--        uMaxBack = uSizeFile;
--
--    buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
--    if (buf==NULL)
--        return 0;
--
--    uBackRead = 4;
--    while (uBackRead<uMaxBack)
--    {
--        uLong uReadSize;
--        ZPOS64_T uReadPos;
--        int i;
--        if (uBackRead+BUFREADCOMMENT>uMaxBack)
--            uBackRead = uMaxBack;
--        else
--            uBackRead+=BUFREADCOMMENT;
--        uReadPos = uSizeFile-uBackRead ;
--
--        uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
--                     (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
--        if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--            break;
--
--        if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
--            break;
--
--        for (i=(int)uReadSize-3; (i--)>0;)
--            if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
--                ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07))
--            {
--                uPosFound = uReadPos+i;
--                break;
--            }
--
--        if (uPosFound!=0)
--            break;
--    }
--    TRYFREE(buf);
--    if (uPosFound == 0)
--        return 0;
--
--    /* Zip64 end of central directory locator */
--    if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0)
--        return 0;
--
--    /* the signature, already checked */
--    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
--        return 0;
--
--    /* number of the disk with the start of the zip64 end of  central directory */
--    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
--        return 0;
--    if (uL != 0)
--        return 0;
--
--    /* relative offset of the zip64 end of central directory record */
--    if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK)
--        return 0;
--
--    /* total number of disks */
--    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
--        return 0;
--    if (uL != 1)
--        return 0;
--
--    /* Goto end of central directory record */
--    if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0)
--        return 0;
--
--     /* the signature */
--    if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
--        return 0;
--
--    if (uL != 0x06064b50)
--        return 0;
--
--    return relativeOffset;
--}
--
--/*
--  Open a Zip file. path contain the full pathname (by example,
--     on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer
--     "zlib/zlib114.zip".
--     If the zipfile cannot be opened (file doesn't exist or in not valid), the
--       return value is NULL.
--     Else, the return value is a unzFile Handle, usable with other function
--       of this unzip package.
--*/
--local unzFile unzOpenInternal (const void *path,
--                               zlib_filefunc64_32_def* pzlib_filefunc64_32_def,
--                               int is64bitOpenFunction)
--{
--    unz64_s us;
--    unz64_s *s;
--    ZPOS64_T central_pos;
--    uLong   uL;
--
--    uLong number_disk;          /* number of the current dist, used for
--                                   spaning ZIP, unsupported, always 0*/
--    uLong number_disk_with_CD;  /* number the the disk with central dir, used
--                                   for spaning ZIP, unsupported, always 0*/
--    ZPOS64_T number_entry_CD;      /* total number of entries in
--                                   the central dir
--                                   (same than number_entry on nospan) */
--
--    int err=UNZ_OK;
--
--    if (unz_copyright[0]!=' ')
--        return NULL;
--
--    us.z_filefunc.zseek32_file = NULL;
--    us.z_filefunc.ztell32_file = NULL;
--    if (pzlib_filefunc64_32_def==NULL)
--        fill_fopen64_filefunc(&us.z_filefunc.zfile_func64);
--    else
--        us.z_filefunc = *pzlib_filefunc64_32_def;
--    us.is64bitOpenFunction = is64bitOpenFunction;
--
--
--
--    us.filestream = ZOPEN64(us.z_filefunc,
--                                                 path,
--                                                 ZLIB_FILEFUNC_MODE_READ |
--                                                 ZLIB_FILEFUNC_MODE_EXISTING);
--    if (us.filestream==NULL)
--        return NULL;
--
--    central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream);
--    if (central_pos)
--    {
--        uLong uS;
--        ZPOS64_T uL64;
--
--        us.isZip64 = 1;
--
--        if (ZSEEK64(us.z_filefunc, us.filestream,
--                                      central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--        err=UNZ_ERRNO;
--
--        /* the signature, already checked */
--        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* size of zip64 end of central directory record */
--        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* version made by */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* version needed to extract */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* number of this disk */
--        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* number of the disk with the start of the central directory */
--        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* total number of entries in the central directory on this disk */
--        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* total number of entries in the central directory */
--        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        if ((number_entry_CD!=us.gi.number_entry) ||
--            (number_disk_with_CD!=0) ||
--            (number_disk!=0))
--            err=UNZ_BADZIPFILE;
--
--        /* size of the central directory */
--        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* offset of start of central directory with respect to the
--          starting disk number */
--        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        us.gi.size_comment = 0;
--    }
--    else
--    {
--        central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream);
--        if (central_pos==0)
--            err=UNZ_ERRNO;
--
--        us.isZip64 = 0;
--
--        if (ZSEEK64(us.z_filefunc, us.filestream,
--                                        central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--            err=UNZ_ERRNO;
--
--        /* the signature, already checked */
--        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* number of this disk */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* number of the disk with the start of the central directory */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
--            err=UNZ_ERRNO;
--
--        /* total number of entries in the central dir on this disk */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
--            err=UNZ_ERRNO;
--        us.gi.number_entry = uL;
--
--        /* total number of entries in the central dir */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
--            err=UNZ_ERRNO;
--        number_entry_CD = uL;
--
--        if ((number_entry_CD!=us.gi.number_entry) ||
--            (number_disk_with_CD!=0) ||
--            (number_disk!=0))
--            err=UNZ_BADZIPFILE;
--
--        /* size of the central directory */
--        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
--            err=UNZ_ERRNO;
--        us.size_central_dir = uL;
--
--        /* offset of start of central directory with respect to the
--            starting disk number */
--        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
--            err=UNZ_ERRNO;
--        us.offset_central_dir = uL;
--
--        /* zipfile comment length */
--        if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK)
--            err=UNZ_ERRNO;
--    }
--
--    if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
--        (err==UNZ_OK))
--        err=UNZ_BADZIPFILE;
--
--    if (err!=UNZ_OK)
--    {
--        ZCLOSE64(us.z_filefunc, us.filestream);
--        return NULL;
--    }
--
--    us.byte_before_the_zipfile = central_pos -
--                            (us.offset_central_dir+us.size_central_dir);
--    us.central_pos = central_pos;
--    us.pfile_in_zip_read = NULL;
--    us.encrypted = 0;
--
--
--    s=(unz64_s*)ALLOC(sizeof(unz64_s));
--    if( s != NULL)
--    {
--        *s=us;
--        unzGoToFirstFile((unzFile)s);
--    }
--    return (unzFile)s;
--}
--
--
--extern unzFile ZEXPORT unzOpen2 (const char *path,
--                                        zlib_filefunc_def* pzlib_filefunc32_def)
--{
--    if (pzlib_filefunc32_def != NULL)
--    {
--        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
--        fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def);
--        return unzOpenInternal(path, &zlib_filefunc64_32_def_fill, 0);
--    }
--    else
--        return unzOpenInternal(path, NULL, 0);
--}
--
--extern unzFile ZEXPORT unzOpen2_64 (const void *path,
--                                     zlib_filefunc64_def* pzlib_filefunc_def)
--{
--    if (pzlib_filefunc_def != NULL)
--    {
--        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
--        zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def;
--        zlib_filefunc64_32_def_fill.ztell32_file = NULL;
--        zlib_filefunc64_32_def_fill.zseek32_file = NULL;
--        return unzOpenInternal(path, &zlib_filefunc64_32_def_fill, 1);
--    }
--    else
--        return unzOpenInternal(path, NULL, 1);
--}
--
--extern unzFile ZEXPORT unzOpen (const char *path)
--{
--    return unzOpenInternal(path, NULL, 0);
--}
--
--extern unzFile ZEXPORT unzOpen64 (const void *path)
--{
--    return unzOpenInternal(path, NULL, 1);
--}
--
--/*
--  Close a ZipFile opened with unzOpen.
--  If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
--    these files MUST be closed with unzCloseCurrentFile before call unzClose.
--  return UNZ_OK if there is no problem. */
--extern int ZEXPORT unzClose (unzFile file)
--{
--    unz64_s* s;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--
--    if (s->pfile_in_zip_read!=NULL)
--        unzCloseCurrentFile(file);
--
--    ZCLOSE64(s->z_filefunc, s->filestream);
--    TRYFREE(s);
--    return UNZ_OK;
--}
--
--
--/*
--  Write info about the ZipFile in the *pglobal_info structure.
--  No preparation of the structure is needed
--  return UNZ_OK if there is no problem. */
--extern int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info)
--{
--    unz64_s* s;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    *pglobal_info=s->gi;
--    return UNZ_OK;
--}
--
--extern int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32)
--{
--    unz64_s* s;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    /* to do : check if number_entry is not truncated */
--    pglobal_info32->number_entry = (uLong)s->gi.number_entry;
--    pglobal_info32->size_comment = s->gi.size_comment;
--    return UNZ_OK;
--}
--/*
--   Translate date/time from Dos format to tm_unz (readable more easilty)
--*/
--local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm)
--{
--    ZPOS64_T uDate;
--    uDate = (ZPOS64_T)(ulDosDate>>16);
--    ptm->tm_mday = (uInt)(uDate&0x1f) ;
--    ptm->tm_mon =  (uInt)((((uDate)&0x1E0)/0x20)-1) ;
--    ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
--
--    ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
--    ptm->tm_min =  (uInt) ((ulDosDate&0x7E0)/0x20) ;
--    ptm->tm_sec =  (uInt) (2*(ulDosDate&0x1f)) ;
--}
--
--/*
--  Get Info about the current file in the zipfile, with internal only info
--*/
--local int unz64local_GetCurrentFileInfoInternal OF((unzFile file,
--                                                  unz_file_info64 *pfile_info,
--                                                  unz_file_info64_internal
--                                                  *pfile_info_internal,
--                                                  char *szFileName,
--                                                  uLong fileNameBufferSize,
--                                                  void *extraField,
--                                                  uLong extraFieldBufferSize,
--                                                  char *szComment,
--                                                  uLong commentBufferSize));
--
--local int unz64local_GetCurrentFileInfoInternal (unzFile file,
--                                                  unz_file_info64 *pfile_info,
--                                                  unz_file_info64_internal
--                                                  *pfile_info_internal,
--                                                  char *szFileName,
--                                                  uLong fileNameBufferSize,
--                                                  void *extraField,
--                                                  uLong extraFieldBufferSize,
--                                                  char *szComment,
--                                                  uLong commentBufferSize)
--{
--    unz64_s* s;
--    unz_file_info64 file_info;
--    unz_file_info64_internal file_info_internal;
--    int err=UNZ_OK;
--    uLong uMagic;
--    long lSeek=0;
--    uLong uL;
--
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    if (ZSEEK64(s->z_filefunc, s->filestream,
--              s->pos_in_central_dir+s->byte_before_the_zipfile,
--              ZLIB_FILEFUNC_SEEK_SET)!=0)
--        err=UNZ_ERRNO;
--
--
--    /* we check the magic */
--    if (err==UNZ_OK)
--    {
--        if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK)
--            err=UNZ_ERRNO;
--        else if (uMagic!=0x02014b50)
--            err=UNZ_BADZIPFILE;
--    }
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
--        err=UNZ_ERRNO;
--    file_info.compressed_size = uL;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
--        err=UNZ_ERRNO;
--    file_info.uncompressed_size = uL;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--                // relative offset of local header
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
--        err=UNZ_ERRNO;
--    file_info_internal.offset_curfile = uL;
--
--    lSeek+=file_info.size_filename;
--    if ((err==UNZ_OK) && (szFileName!=NULL))
--    {
--        uLong uSizeRead ;
--        if (file_info.size_filename<fileNameBufferSize)
--        {
--            *(szFileName+file_info.size_filename)='\0';
--            uSizeRead = file_info.size_filename;
--        }
--        else
--            uSizeRead = fileNameBufferSize;
--
--        if ((file_info.size_filename>0) && (fileNameBufferSize>0))
--            if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead)
--                err=UNZ_ERRNO;
--        lSeek -= uSizeRead;
--    }
--
--    // Read extrafield
--    if ((err==UNZ_OK) && (extraField!=NULL))
--    {
--        ZPOS64_T uSizeRead ;
--        if (file_info.size_file_extra<extraFieldBufferSize)
--            uSizeRead = file_info.size_file_extra;
--        else
--            uSizeRead = extraFieldBufferSize;
--
--        if (lSeek!=0)
--        {
--            if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
--                lSeek=0;
--            else
--                err=UNZ_ERRNO;
--        }
--
--        if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
--            if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead)
--                err=UNZ_ERRNO;
--
--        lSeek += file_info.size_file_extra - (uLong)uSizeRead;
--    }
--    else
--        lSeek += file_info.size_file_extra;
--
--
--    if ((err==UNZ_OK) && (file_info.size_file_extra != 0))
--    {
--                                uLong acc = 0;
--
--        // since lSeek now points to after the extra field we need to move back
--        lSeek -= file_info.size_file_extra;
--
--        if (lSeek!=0)
--        {
--            if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
--                lSeek=0;
--            else
--                err=UNZ_ERRNO;
--        }
--
--        while(acc < file_info.size_file_extra)
--        {
--            uLong headerId;
--                                                uLong dataSize;
--
--            if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK)
--                err=UNZ_ERRNO;
--
--            if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK)
--                err=UNZ_ERRNO;
--
--            /* ZIP64 extra fields */
--            if (headerId == 0x0001)
--            {
--                                                        uLong uL;
--
--                                                                if(file_info.uncompressed_size == MAXU32)
--                                                                {
--                                                                        if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK)
--                                                                                        err=UNZ_ERRNO;
--                                                                }
--
--                                                                if(file_info.compressed_size == MAXU32)
--                                                                {
--                                                                        if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK)
--                                                                                  err=UNZ_ERRNO;
--                                                                }
--
--                                                                if(file_info_internal.offset_curfile == MAXU32)
--                                                                {
--                                                                        /* Relative Header offset */
--                                                                        if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK)
--                                                                                err=UNZ_ERRNO;
--                                                                }
--
--                                                                if(file_info.disk_num_start == MAXU32)
--                                                                {
--                                                                        /* Disk Start Number */
--                                                                        if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK)
--                                                                                err=UNZ_ERRNO;
--                                                                }
--
--            }
--            else
--            {
--                if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0)
--                    err=UNZ_ERRNO;
--            }
--
--            acc += 2 + 2 + dataSize;
--        }
--    }
--
--    if ((err==UNZ_OK) && (szComment!=NULL))
--    {
--        uLong uSizeRead ;
--        if (file_info.size_file_comment<commentBufferSize)
--        {
--            *(szComment+file_info.size_file_comment)='\0';
--            uSizeRead = file_info.size_file_comment;
--        }
--        else
--            uSizeRead = commentBufferSize;
--
--        if (lSeek!=0)
--        {
--            if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
--                lSeek=0;
--            else
--                err=UNZ_ERRNO;
--        }
--
--        if ((file_info.size_file_comment>0) && (commentBufferSize>0))
--            if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead)
--                err=UNZ_ERRNO;
--        lSeek+=file_info.size_file_comment - uSizeRead;
--    }
--    else
--        lSeek+=file_info.size_file_comment;
--
--
--    if ((err==UNZ_OK) && (pfile_info!=NULL))
--        *pfile_info=file_info;
--
--    if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
--        *pfile_info_internal=file_info_internal;
--
--    return err;
--}
--
--
--
--/*
--  Write info about the ZipFile in the *pglobal_info structure.
--  No preparation of the structure is needed
--  return UNZ_OK if there is no problem.
--*/
--extern int ZEXPORT unzGetCurrentFileInfo64 (unzFile file,
--                                          unz_file_info64 * pfile_info,
--                                          char * szFileName, uLong fileNameBufferSize,
--                                          void *extraField, uLong extraFieldBufferSize,
--                                          char* szComment,  uLong commentBufferSize)
--{
--    return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL,
--                                                szFileName,fileNameBufferSize,
--                                                extraField,extraFieldBufferSize,
--                                                szComment,commentBufferSize);
--}
--
--extern int ZEXPORT unzGetCurrentFileInfo (unzFile file,
--                                          unz_file_info * pfile_info,
--                                          char * szFileName, uLong fileNameBufferSize,
--                                          void *extraField, uLong extraFieldBufferSize,
--                                          char* szComment,  uLong commentBufferSize)
--{
--    int err;
--    unz_file_info64 file_info64;
--    err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL,
--                                                szFileName,fileNameBufferSize,
--                                                extraField,extraFieldBufferSize,
--                                                szComment,commentBufferSize);
--    if ((err==UNZ_OK) && (pfile_info != NULL))
--    {
--        pfile_info->version = file_info64.version;
--        pfile_info->version_needed = file_info64.version_needed;
--        pfile_info->flag = file_info64.flag;
--        pfile_info->compression_method = file_info64.compression_method;
--        pfile_info->dosDate = file_info64.dosDate;
--        pfile_info->crc = file_info64.crc;
--
--        pfile_info->size_filename = file_info64.size_filename;
--        pfile_info->size_file_extra = file_info64.size_file_extra;
--        pfile_info->size_file_comment = file_info64.size_file_comment;
--
--        pfile_info->disk_num_start = file_info64.disk_num_start;
--        pfile_info->internal_fa = file_info64.internal_fa;
--        pfile_info->external_fa = file_info64.external_fa;
--
--        pfile_info->tmu_date = file_info64.tmu_date,
--
--
--        pfile_info->compressed_size = (uLong)file_info64.compressed_size;
--        pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size;
--
--    }
--    return err;
--}
--/*
--  Set the current file of the zipfile to the first file.
--  return UNZ_OK if there is no problem
--*/
--extern int ZEXPORT unzGoToFirstFile (unzFile file)
--{
--    int err=UNZ_OK;
--    unz64_s* s;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    s->pos_in_central_dir=s->offset_central_dir;
--    s->num_file=0;
--    err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
--                                             &s->cur_file_info_internal,
--                                             NULL,0,NULL,0,NULL,0);
--    s->current_file_ok = (err == UNZ_OK);
--    return err;
--}
--
--/*
--  Set the current file of the zipfile to the next file.
--  return UNZ_OK if there is no problem
--  return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
--*/
--extern int ZEXPORT unzGoToNextFile (unzFile  file)
--{
--    unz64_s* s;
--    int err;
--
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    if (!s->current_file_ok)
--        return UNZ_END_OF_LIST_OF_FILE;
--    if (s->gi.number_entry != 0xffff)    /* 2^16 files overflow hack */
--      if (s->num_file+1==s->gi.number_entry)
--        return UNZ_END_OF_LIST_OF_FILE;
--
--    s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
--            s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
--    s->num_file++;
--    err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
--                                               &s->cur_file_info_internal,
--                                               NULL,0,NULL,0,NULL,0);
--    s->current_file_ok = (err == UNZ_OK);
--    return err;
--}
--
--
--/*
--  Try locate the file szFileName in the zipfile.
--  For the iCaseSensitivity signification, see unzStringFileNameCompare
--
--  return value :
--  UNZ_OK if the file is found. It becomes the current file.
--  UNZ_END_OF_LIST_OF_FILE if the file is not found
--*/
--extern int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
--{
--    unz64_s* s;
--    int err;
--
--    /* We remember the 'current' position in the file so that we can jump
--     * back there if we fail.
--     */
--    unz_file_info64 cur_file_infoSaved;
--    unz_file_info64_internal cur_file_info_internalSaved;
--    ZPOS64_T num_fileSaved;
--    ZPOS64_T pos_in_central_dirSaved;
--
--
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--
--    if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
--        return UNZ_PARAMERROR;
--
--    s=(unz64_s*)file;
--    if (!s->current_file_ok)
--        return UNZ_END_OF_LIST_OF_FILE;
--
--    /* Save the current state */
--    num_fileSaved = s->num_file;
--    pos_in_central_dirSaved = s->pos_in_central_dir;
--    cur_file_infoSaved = s->cur_file_info;
--    cur_file_info_internalSaved = s->cur_file_info_internal;
--
--    err = unzGoToFirstFile(file);
--
--    while (err == UNZ_OK)
--    {
--        char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
--        err = unzGetCurrentFileInfo64(file,NULL,
--                                    szCurrentFileName,sizeof(szCurrentFileName)-1,
--                                    NULL,0,NULL,0);
--        if (err == UNZ_OK)
--        {
--            if (unzStringFileNameCompare(szCurrentFileName,
--                                            szFileName,iCaseSensitivity)==0)
--                return UNZ_OK;
--            err = unzGoToNextFile(file);
--        }
--    }
--
--    /* We failed, so restore the state of the 'current file' to where we
--     * were.
--     */
--    s->num_file = num_fileSaved ;
--    s->pos_in_central_dir = pos_in_central_dirSaved ;
--    s->cur_file_info = cur_file_infoSaved;
--    s->cur_file_info_internal = cur_file_info_internalSaved;
--    return err;
--}
--
--
--/*
--///////////////////////////////////////////
--// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net)
--// I need random access
--//
--// Further optimization could be realized by adding an ability
--// to cache the directory in memory. The goal being a single
--// comprehensive file read to put the file I need in a memory.
--*/
--
--/*
--typedef struct unz_file_pos_s
--{
--    ZPOS64_T pos_in_zip_directory;   // offset in file
--    ZPOS64_T num_of_file;            // # of file
--} unz_file_pos;
--*/
--
--extern int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos*  file_pos)
--{
--    unz64_s* s;
--
--    if (file==NULL || file_pos==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    if (!s->current_file_ok)
--        return UNZ_END_OF_LIST_OF_FILE;
--
--    file_pos->pos_in_zip_directory  = s->pos_in_central_dir;
--    file_pos->num_of_file           = s->num_file;
--
--    return UNZ_OK;
--}
--
--extern int ZEXPORT unzGetFilePos(
--    unzFile file,
--    unz_file_pos* file_pos)
--{
--    unz64_file_pos file_pos64;
--    int err = unzGetFilePos64(file,&file_pos64);
--    if (err==UNZ_OK)
--    {
--        file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory;
--        file_pos->num_of_file = (uLong)file_pos64.num_of_file;
--    }
--    return err;
--}
--
--extern int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos)
--{
--    unz64_s* s;
--    int err;
--
--    if (file==NULL || file_pos==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--
--    /* jump to the right spot */
--    s->pos_in_central_dir = file_pos->pos_in_zip_directory;
--    s->num_file           = file_pos->num_of_file;
--
--    /* set the current file */
--    err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
--                                               &s->cur_file_info_internal,
--                                               NULL,0,NULL,0,NULL,0);
--    /* return results */
--    s->current_file_ok = (err == UNZ_OK);
--    return err;
--}
--
--extern int ZEXPORT unzGoToFilePos(
--    unzFile file,
--    unz_file_pos* file_pos)
--{
--    unz64_file_pos file_pos64;
--    if (file_pos == NULL)
--        return UNZ_PARAMERROR;
--
--    file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory;
--    file_pos64.num_of_file = file_pos->num_of_file;
--    return unzGoToFilePos64(file,&file_pos64);
--}
--
--/*
--// Unzip Helper Functions - should be here?
--///////////////////////////////////////////
--*/
--
--/*
--  Read the local header of the current zipfile
--  Check the coherency of the local header and info in the end of central
--        directory about this file
--  store in *piSizeVar the size of extra info in local header
--        (filename and size of extra field data)
--*/
--local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar,
--                                                    ZPOS64_T * poffset_local_extrafield,
--                                                    uInt  * psize_local_extrafield)
--{
--    uLong uMagic,uData,uFlags;
--    uLong size_filename;
--    uLong size_extra_field;
--    int err=UNZ_OK;
--
--    *piSizeVar = 0;
--    *poffset_local_extrafield = 0;
--    *psize_local_extrafield = 0;
--
--    if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile +
--                                s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0)
--        return UNZ_ERRNO;
--
--
--    if (err==UNZ_OK)
--    {
--        if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK)
--            err=UNZ_ERRNO;
--        else if (uMagic!=0x04034b50)
--            err=UNZ_BADZIPFILE;
--    }
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK)
--        err=UNZ_ERRNO;
--/*
--    else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
--        err=UNZ_BADZIPFILE;
--*/
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK)
--        err=UNZ_ERRNO;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK)
--        err=UNZ_ERRNO;
--    else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
--        err=UNZ_BADZIPFILE;
--
--    if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
--/* #ifdef HAVE_BZIP2 */
--                         (s->cur_file_info.compression_method!=Z_BZIP2ED) &&
--/* #endif */
--                         (s->cur_file_info.compression_method!=Z_DEFLATED))
--        err=UNZ_BADZIPFILE;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */
--        err=UNZ_ERRNO;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */
--        err=UNZ_ERRNO;
--    else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0))
--        err=UNZ_BADZIPFILE;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */
--        err=UNZ_ERRNO;
--    else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0))
--        err=UNZ_BADZIPFILE;
--
--    if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */
--        err=UNZ_ERRNO;
--    else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0))
--        err=UNZ_BADZIPFILE;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK)
--        err=UNZ_ERRNO;
--    else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
--        err=UNZ_BADZIPFILE;
--
--    *piSizeVar += (uInt)size_filename;
--
--    if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK)
--        err=UNZ_ERRNO;
--    *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
--                                    SIZEZIPLOCALHEADER + size_filename;
--    *psize_local_extrafield = (uInt)size_extra_field;
--
--    *piSizeVar += (uInt)size_extra_field;
--
--    return err;
--}
--
--/*
--  Open for reading data the current file in the zipfile.
--  If there is no error and the file is opened, the return value is UNZ_OK.
--*/
--extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method,
--                                            int* level, int raw, const char* password)
--{
--    int err=UNZ_OK;
--    uInt iSizeVar;
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    ZPOS64_T offset_local_extrafield;  /* offset of the local extra field */
--    uInt  size_local_extrafield;    /* size of the local extra field */
--#    ifndef NOUNCRYPT
--    char source[12];
--#    else
--    if (password != NULL)
--        return UNZ_PARAMERROR;
--#    endif
--
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    if (!s->current_file_ok)
--        return UNZ_PARAMERROR;
--
--    if (s->pfile_in_zip_read != NULL)
--        unzCloseCurrentFile(file);
--
--    if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
--        return UNZ_BADZIPFILE;
--
--    pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s));
--    if (pfile_in_zip_read_info==NULL)
--        return UNZ_INTERNALERROR;
--
--    pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
--    pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
--    pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
--    pfile_in_zip_read_info->pos_local_extrafield=0;
--    pfile_in_zip_read_info->raw=raw;
--
--    if (pfile_in_zip_read_info->read_buffer==NULL)
--    {
--        TRYFREE(pfile_in_zip_read_info);
--        return UNZ_INTERNALERROR;
--    }
--
--    pfile_in_zip_read_info->stream_initialised=0;
--
--    if (method!=NULL)
--        *method = (int)s->cur_file_info.compression_method;
--
--    if (level!=NULL)
--    {
--        *level = 6;
--        switch (s->cur_file_info.flag & 0x06)
--        {
--          case 6 : *level = 1; break;
--          case 4 : *level = 2; break;
--          case 2 : *level = 9; break;
--        }
--    }
--
--    if ((s->cur_file_info.compression_method!=0) &&
--/* #ifdef HAVE_BZIP2 */
--        (s->cur_file_info.compression_method!=Z_BZIP2ED) &&
--/* #endif */
--        (s->cur_file_info.compression_method!=Z_DEFLATED))
--
--        err=UNZ_BADZIPFILE;
--
--    pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
--    pfile_in_zip_read_info->crc32=0;
--    pfile_in_zip_read_info->total_out_64=0;
--    pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method;
--    pfile_in_zip_read_info->filestream=s->filestream;
--    pfile_in_zip_read_info->z_filefunc=s->z_filefunc;
--    pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
--
--    pfile_in_zip_read_info->stream.total_out = 0;
--
--    if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw))
--    {
--#ifdef HAVE_BZIP2
--      pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0;
--      pfile_in_zip_read_info->bstream.bzfree = (free_func)0;
--      pfile_in_zip_read_info->bstream.opaque = (voidpf)0;
--      pfile_in_zip_read_info->bstream.state = (voidpf)0;
--
--      pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
--      pfile_in_zip_read_info->stream.zfree = (free_func)0;
--      pfile_in_zip_read_info->stream.opaque = (voidpf)0;
--      pfile_in_zip_read_info->stream.next_in = (voidpf)0;
--      pfile_in_zip_read_info->stream.avail_in = 0;
--
--      err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0);
--      if (err == Z_OK)
--        pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED;
--      else
--      {
--        TRYFREE(pfile_in_zip_read_info);
--        return err;
--      }
--#else
--      pfile_in_zip_read_info->raw=1;
--#endif
--    }
--    else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw))
--    {
--      pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
--      pfile_in_zip_read_info->stream.zfree = (free_func)0;
--      pfile_in_zip_read_info->stream.opaque = (voidpf)0;
--      pfile_in_zip_read_info->stream.next_in = 0;
--      pfile_in_zip_read_info->stream.avail_in = 0;
--
--      err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
--      if (err == Z_OK)
--        pfile_in_zip_read_info->stream_initialised=Z_DEFLATED;
--      else
--      {
--        TRYFREE(pfile_in_zip_read_info);
--        return err;
--      }
--        /* windowBits is passed < 0 to tell that there is no zlib header.
--         * Note that in this case inflate *requires* an extra "dummy" byte
--         * after the compressed stream in order to complete decompression and
--         * return Z_STREAM_END.
--         * In unzip, i don't wait absolutely Z_STREAM_END because I known the
--         * size of both compressed and uncompressed data
--         */
--    }
--    pfile_in_zip_read_info->rest_read_compressed =
--            s->cur_file_info.compressed_size ;
--    pfile_in_zip_read_info->rest_read_uncompressed =
--            s->cur_file_info.uncompressed_size ;
--
--
--    pfile_in_zip_read_info->pos_in_zipfile =
--            s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
--              iSizeVar;
--
--    pfile_in_zip_read_info->stream.avail_in = (uInt)0;
--
--    s->pfile_in_zip_read = pfile_in_zip_read_info;
--                s->encrypted = 0;
--
--#    ifndef NOUNCRYPT
--    if (password != NULL)
--    {
--        int i;
--        s->pcrc_32_tab = get_crc_table();
--        init_keys(password,s->keys,s->pcrc_32_tab);
--        if (ZSEEK64(s->z_filefunc, s->filestream,
--                  s->pfile_in_zip_read->pos_in_zipfile +
--                     s->pfile_in_zip_read->byte_before_the_zipfile,
--                  SEEK_SET)!=0)
--            return UNZ_INTERNALERROR;
--        if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12)
--            return UNZ_INTERNALERROR;
--
--        for (i = 0; i<12; i++)
--            zdecode(s->keys,s->pcrc_32_tab,source[i]);
--
--        s->pfile_in_zip_read->pos_in_zipfile+=12;
--        s->encrypted=1;
--    }
--#    endif
--
--
--    return UNZ_OK;
--}
--
--extern int ZEXPORT unzOpenCurrentFile (unzFile file)
--{
--    return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL);
--}
--
--extern int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char*  password)
--{
--    return unzOpenCurrentFile3(file, NULL, NULL, 0, password);
--}
--
--extern int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw)
--{
--    return unzOpenCurrentFile3(file, method, level, raw, NULL);
--}
--
--/** Addition for GDAL : START */
--
--extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file)
--{
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    s=(unz64_s*)file;
--    if (file==NULL)
--        return 0; //UNZ_PARAMERROR;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--    if (pfile_in_zip_read_info==NULL)
--        return 0; //UNZ_PARAMERROR;
--    return pfile_in_zip_read_info->pos_in_zipfile +
--                         pfile_in_zip_read_info->byte_before_the_zipfile;
--}
--
--/** Addition for GDAL : END */
--
--/*
--  Read bytes from the current file.
--  buf contain buffer where data must be copied
--  len the size of buf.
--
--  return the number of byte copied if somes bytes are copied
--  return 0 if the end of file was reached
--  return <0 with error code if there is an error
--    (UNZ_ERRNO for IO error, or zLib error for uncompress error)
--*/
--extern int ZEXPORT unzReadCurrentFile  (unzFile file, voidp buf, unsigned len)
--{
--    int err=UNZ_OK;
--    uInt iRead = 0;
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--
--    if (pfile_in_zip_read_info==NULL)
--        return UNZ_PARAMERROR;
--
--
--    if (pfile_in_zip_read_info->read_buffer == NULL)
--        return UNZ_END_OF_LIST_OF_FILE;
--    if (len==0)
--        return 0;
--
--    pfile_in_zip_read_info->stream.next_out = (Bytef*)buf;
--
--    pfile_in_zip_read_info->stream.avail_out = (uInt)len;
--
--    if ((len>pfile_in_zip_read_info->rest_read_uncompressed) &&
--        (!(pfile_in_zip_read_info->raw)))
--        pfile_in_zip_read_info->stream.avail_out =
--            (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
--
--    if ((len>pfile_in_zip_read_info->rest_read_compressed+
--           pfile_in_zip_read_info->stream.avail_in) &&
--         (pfile_in_zip_read_info->raw))
--        pfile_in_zip_read_info->stream.avail_out =
--            (uInt)pfile_in_zip_read_info->rest_read_compressed+
--            pfile_in_zip_read_info->stream.avail_in;
--
--    while (pfile_in_zip_read_info->stream.avail_out>0)
--    {
--        if ((pfile_in_zip_read_info->stream.avail_in==0) &&
--            (pfile_in_zip_read_info->rest_read_compressed>0))
--        {
--            uInt uReadThis = UNZ_BUFSIZE;
--            if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
--                uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
--            if (uReadThis == 0)
--                return UNZ_EOF;
--            if (ZSEEK64(pfile_in_zip_read_info->z_filefunc,
--                      pfile_in_zip_read_info->filestream,
--                      pfile_in_zip_read_info->pos_in_zipfile +
--                         pfile_in_zip_read_info->byte_before_the_zipfile,
--                         ZLIB_FILEFUNC_SEEK_SET)!=0)
--                return UNZ_ERRNO;
--            if (ZREAD64(pfile_in_zip_read_info->z_filefunc,
--                      pfile_in_zip_read_info->filestream,
--                      pfile_in_zip_read_info->read_buffer,
--                      uReadThis)!=uReadThis)
--                return UNZ_ERRNO;
--
--
--#            ifndef NOUNCRYPT
--            if(s->encrypted)
--            {
--                uInt i;
--                for(i=0;i<uReadThis;i++)
--                  pfile_in_zip_read_info->read_buffer[i] =
--                      zdecode(s->keys,s->pcrc_32_tab,
--                              pfile_in_zip_read_info->read_buffer[i]);
--            }
--#            endif
--
--
--            pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
--
--            pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
--
--            pfile_in_zip_read_info->stream.next_in =
--                (Bytef*)pfile_in_zip_read_info->read_buffer;
--            pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
--        }
--
--        if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw))
--        {
--            uInt uDoCopy,i ;
--
--            if ((pfile_in_zip_read_info->stream.avail_in == 0) &&
--                (pfile_in_zip_read_info->rest_read_compressed == 0))
--                return (iRead==0) ? UNZ_EOF : iRead;
--
--            if (pfile_in_zip_read_info->stream.avail_out <
--                            pfile_in_zip_read_info->stream.avail_in)
--                uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
--            else
--                uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
--
--            for (i=0;i<uDoCopy;i++)
--                *(pfile_in_zip_read_info->stream.next_out+i) =
--                        *(pfile_in_zip_read_info->stream.next_in+i);
--
--            pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy;
--
--            pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
--                                pfile_in_zip_read_info->stream.next_out,
--                                uDoCopy);
--            pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
--            pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
--            pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
--            pfile_in_zip_read_info->stream.next_out += uDoCopy;
--            pfile_in_zip_read_info->stream.next_in += uDoCopy;
--            pfile_in_zip_read_info->stream.total_out += uDoCopy;
--            iRead += uDoCopy;
--        }
--        else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED)
--        {
--#ifdef HAVE_BZIP2
--            uLong uTotalOutBefore,uTotalOutAfter;
--            const Bytef *bufBefore;
--            uLong uOutThis;
--
--            pfile_in_zip_read_info->bstream.next_in        = (char*)pfile_in_zip_read_info->stream.next_in;
--            pfile_in_zip_read_info->bstream.avail_in       = pfile_in_zip_read_info->stream.avail_in;
--            pfile_in_zip_read_info->bstream.total_in_lo32  = pfile_in_zip_read_info->stream.total_in;
--            pfile_in_zip_read_info->bstream.total_in_hi32  = 0;
--            pfile_in_zip_read_info->bstream.next_out       = (char*)pfile_in_zip_read_info->stream.next_out;
--            pfile_in_zip_read_info->bstream.avail_out      = pfile_in_zip_read_info->stream.avail_out;
--            pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out;
--            pfile_in_zip_read_info->bstream.total_out_hi32 = 0;
--
--            uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32;
--            bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out;
--
--            err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream);
--
--            uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32;
--            uOutThis = uTotalOutAfter-uTotalOutBefore;
--
--            pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis;
--
--            pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis));
--            pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis;
--            iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
--
--            pfile_in_zip_read_info->stream.next_in   = (Bytef*)pfile_in_zip_read_info->bstream.next_in;
--            pfile_in_zip_read_info->stream.avail_in  = pfile_in_zip_read_info->bstream.avail_in;
--            pfile_in_zip_read_info->stream.total_in  = pfile_in_zip_read_info->bstream.total_in_lo32;
--            pfile_in_zip_read_info->stream.next_out  = (Bytef*)pfile_in_zip_read_info->bstream.next_out;
--            pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out;
--            pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32;
--
--            if (err==BZ_STREAM_END)
--              return (iRead==0) ? UNZ_EOF : iRead;
--            if (err!=BZ_OK)
--              break;
--#endif
--        } // end Z_BZIP2ED
--        else
--        {
--            ZPOS64_T uTotalOutBefore,uTotalOutAfter;
--            const Bytef *bufBefore;
--            ZPOS64_T uOutThis;
--            int flush=Z_SYNC_FLUSH;
--
--            uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
--            bufBefore = pfile_in_zip_read_info->stream.next_out;
--
--            /*
--            if ((pfile_in_zip_read_info->rest_read_uncompressed ==
--                     pfile_in_zip_read_info->stream.avail_out) &&
--                (pfile_in_zip_read_info->rest_read_compressed == 0))
--                flush = Z_FINISH;
--            */
--            err=inflate(&pfile_in_zip_read_info->stream,flush);
--
--            if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL))
--              err = Z_DATA_ERROR;
--
--            uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
--            uOutThis = uTotalOutAfter-uTotalOutBefore;
--
--            pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis;
--
--            pfile_in_zip_read_info->crc32 =
--                crc32(pfile_in_zip_read_info->crc32,bufBefore,
--                        (uInt)(uOutThis));
--
--            pfile_in_zip_read_info->rest_read_uncompressed -=
--                uOutThis;
--
--            iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
--
--            if (err==Z_STREAM_END)
--                return (iRead==0) ? UNZ_EOF : iRead;
--            if (err!=Z_OK)
--                break;
--        }
--    }
--
--    if (err==Z_OK)
--        return iRead;
--    return err;
--}
--
--
--/*
--  Give the current position in uncompressed data
--*/
--extern z_off_t ZEXPORT unztell (unzFile file)
--{
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--
--    if (pfile_in_zip_read_info==NULL)
--        return UNZ_PARAMERROR;
--
--    return (z_off_t)pfile_in_zip_read_info->stream.total_out;
--}
--
--extern ZPOS64_T ZEXPORT unztell64 (unzFile file)
--{
--
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    if (file==NULL)
--        return (ZPOS64_T)-1;
--    s=(unz64_s*)file;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--
--    if (pfile_in_zip_read_info==NULL)
--        return (ZPOS64_T)-1;
--
--    return pfile_in_zip_read_info->total_out_64;
--}
--
--
--/*
--  return 1 if the end of file was reached, 0 elsewhere
--*/
--extern int ZEXPORT unzeof (unzFile file)
--{
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--
--    if (pfile_in_zip_read_info==NULL)
--        return UNZ_PARAMERROR;
--
--    if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
--        return 1;
--    else
--        return 0;
--}
--
--
--
--/*
--Read extra field from the current file (opened by unzOpenCurrentFile)
--This is the local-header version of the extra field (sometimes, there is
--more info in the local-header version than in the central-header)
--
--  if buf==NULL, it return the size of the local extra field that can be read
--
--  if buf!=NULL, len is the size of the buffer, the extra header is copied in
--    buf.
--  the return value is the number of bytes copied in buf, or (if <0)
--    the error code
--*/
--extern int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len)
--{
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    uInt read_now;
--    ZPOS64_T size_to_read;
--
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--
--    if (pfile_in_zip_read_info==NULL)
--        return UNZ_PARAMERROR;
--
--    size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
--                pfile_in_zip_read_info->pos_local_extrafield);
--
--    if (buf==NULL)
--        return (int)size_to_read;
--
--    if (len>size_to_read)
--        read_now = (uInt)size_to_read;
--    else
--        read_now = (uInt)len ;
--
--    if (read_now==0)
--        return 0;
--
--    if (ZSEEK64(pfile_in_zip_read_info->z_filefunc,
--              pfile_in_zip_read_info->filestream,
--              pfile_in_zip_read_info->offset_local_extrafield +
--              pfile_in_zip_read_info->pos_local_extrafield,
--              ZLIB_FILEFUNC_SEEK_SET)!=0)
--        return UNZ_ERRNO;
--
--    if (ZREAD64(pfile_in_zip_read_info->z_filefunc,
--              pfile_in_zip_read_info->filestream,
--              buf,read_now)!=read_now)
--        return UNZ_ERRNO;
--
--    return (int)read_now;
--}
--
--/*
--  Close the file in zip opened with unzOpenCurrentFile
--  Return UNZ_CRCERROR if all the file was read but the CRC is not good
--*/
--extern int ZEXPORT unzCloseCurrentFile (unzFile file)
--{
--    int err=UNZ_OK;
--
--    unz64_s* s;
--    file_in_zip64_read_info_s* pfile_in_zip_read_info;
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    pfile_in_zip_read_info=s->pfile_in_zip_read;
--
--    if (pfile_in_zip_read_info==NULL)
--        return UNZ_PARAMERROR;
--
--
--    if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) &&
--        (!pfile_in_zip_read_info->raw))
--    {
--        if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
--            err=UNZ_CRCERROR;
--    }
--
--
--    TRYFREE(pfile_in_zip_read_info->read_buffer);
--    pfile_in_zip_read_info->read_buffer = NULL;
--    if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED)
--        inflateEnd(&pfile_in_zip_read_info->stream);
--#ifdef HAVE_BZIP2
--    else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED)
--        BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream);
--#endif
--
--
--    pfile_in_zip_read_info->stream_initialised = 0;
--    TRYFREE(pfile_in_zip_read_info);
--
--    s->pfile_in_zip_read=NULL;
--
--    return err;
--}
--
--
--/*
--  Get the global comment string of the ZipFile, in the szComment buffer.
--  uSizeBuf is the size of the szComment buffer.
--  return the number of byte copied or an error code <0
--*/
--extern int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf)
--{
--    unz64_s* s;
--    uLong uReadThis ;
--    if (file==NULL)
--        return (int)UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--
--    uReadThis = uSizeBuf;
--    if (uReadThis>s->gi.size_comment)
--        uReadThis = s->gi.size_comment;
--
--    if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0)
--        return UNZ_ERRNO;
--
--    if (uReadThis>0)
--    {
--      *szComment='\0';
--      if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis)
--        return UNZ_ERRNO;
--    }
--
--    if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
--        *(szComment+s->gi.size_comment)='\0';
--    return (int)uReadThis;
--}
--
--/* Additions by RX '2004 */
--extern ZPOS64_T ZEXPORT unzGetOffset64(unzFile file)
--{
--    unz64_s* s;
--
--    if (file==NULL)
--          return 0; //UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--    if (!s->current_file_ok)
--      return 0;
--    if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff)
--      if (s->num_file==s->gi.number_entry)
--         return 0;
--    return s->pos_in_central_dir;
--}
--
--extern uLong ZEXPORT unzGetOffset (unzFile file)
--{
--    ZPOS64_T offset64;
--
--    if (file==NULL)
--          return 0; //UNZ_PARAMERROR;
--    offset64 = unzGetOffset64(file);
--    return (uLong)offset64;
--}
--
--extern int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos)
--{
--    unz64_s* s;
--    int err;
--
--    if (file==NULL)
--        return UNZ_PARAMERROR;
--    s=(unz64_s*)file;
--
--    s->pos_in_central_dir = pos;
--    s->num_file = s->gi.number_entry;      /* hack */
--    err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info,
--                                              &s->cur_file_info_internal,
--                                              NULL,0,NULL,0,NULL,0);
--    s->current_file_ok = (err == UNZ_OK);
--    return err;
--}
--
--extern int ZEXPORT unzSetOffset (unzFile file, uLong pos)
--{
--    return unzSetOffset64(file,pos);
--}
diff --cc zlib/contrib/minizip/unzip.h
index 2104e39150749b496ecfac6cabb266488c4777d4,2104e39150749b496ecfac6cabb266488c4777d4..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,437 -1,437 +1,0 @@@
--/* unzip.h -- IO for uncompress .zip files using zlib
--   Version 1.1, February 14h, 2010
--   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications of Unzip for Zip64
--         Copyright (C) 2007-2008 Even Rouault
--
--         Modifications for Zip64 support on both zip and unzip
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--         ---------------------------------------------------------------------------------
--
--        Condition of use and distribution are the same than zlib :
--
--  This software is provided 'as-is', without any express or implied
--  warranty.  In no event will the authors be held liable for any damages
--  arising from the use of this software.
--
--  Permission is granted to anyone to use this software for any purpose,
--  including commercial applications, and to alter it and redistribute it
--  freely, subject to the following restrictions:
--
--  1. The origin of this software must not be misrepresented; you must not
--     claim that you wrote the original software. If you use this software
--     in a product, an acknowledgment in the product documentation would be
--     appreciated but is not required.
--  2. Altered source versions must be plainly marked as such, and must not be
--     misrepresented as being the original software.
--  3. This notice may not be removed or altered from any source distribution.
--
--  ---------------------------------------------------------------------------------
--
--        Changes
--
--        See header of unzip64.c
--
--*/
--
--#ifndef _unz64_H
--#define _unz64_H
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--#ifndef _ZLIB_H
--#include "zlib.h"
--#endif
--
--#ifndef  _ZLIBIOAPI_H
--#include "ioapi.h"
--#endif
--
--#ifdef HAVE_BZIP2
--#include "bzlib.h"
--#endif
--
--#define Z_BZIP2ED 12
--
--#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
--/* like the STRICT of WIN32, we define a pointer that cannot be converted
--    from (void*) without cast */
--typedef struct TagunzFile__ { int unused; } unzFile__;
--typedef unzFile__ *unzFile;
--#else
--typedef voidp unzFile;
--#endif
--
--
--#define UNZ_OK                          (0)
--#define UNZ_END_OF_LIST_OF_FILE         (-100)
--#define UNZ_ERRNO                       (Z_ERRNO)
--#define UNZ_EOF                         (0)
--#define UNZ_PARAMERROR                  (-102)
--#define UNZ_BADZIPFILE                  (-103)
--#define UNZ_INTERNALERROR               (-104)
--#define UNZ_CRCERROR                    (-105)
--
--/* tm_unz contain date/time info */
--typedef struct tm_unz_s
--{
--    uInt tm_sec;            /* seconds after the minute - [0,59] */
--    uInt tm_min;            /* minutes after the hour - [0,59] */
--    uInt tm_hour;           /* hours since midnight - [0,23] */
--    uInt tm_mday;           /* day of the month - [1,31] */
--    uInt tm_mon;            /* months since January - [0,11] */
--    uInt tm_year;           /* years - [1980..2044] */
--} tm_unz;
--
--/* unz_global_info structure contain global data about the ZIPfile
--   These data comes from the end of central dir */
--typedef struct unz_global_info64_s
--{
--    ZPOS64_T number_entry;         /* total number of entries in
--                                     the central dir on this disk */
--    uLong size_comment;         /* size of the global comment of the zipfile */
--} unz_global_info64;
--
--typedef struct unz_global_info_s
--{
--    uLong number_entry;         /* total number of entries in
--                                     the central dir on this disk */
--    uLong size_comment;         /* size of the global comment of the zipfile */
--} unz_global_info;
--
--/* unz_file_info contain information about a file in the zipfile */
--typedef struct unz_file_info64_s
--{
--    uLong version;              /* version made by                 2 bytes */
--    uLong version_needed;       /* version needed to extract       2 bytes */
--    uLong flag;                 /* general purpose bit flag        2 bytes */
--    uLong compression_method;   /* compression method              2 bytes */
--    uLong dosDate;              /* last mod file date in Dos fmt   4 bytes */
--    uLong crc;                  /* crc-32                          4 bytes */
--    ZPOS64_T compressed_size;   /* compressed size                 8 bytes */
--    ZPOS64_T uncompressed_size; /* uncompressed size               8 bytes */
--    uLong size_filename;        /* filename length                 2 bytes */
--    uLong size_file_extra;      /* extra field length              2 bytes */
--    uLong size_file_comment;    /* file comment length             2 bytes */
--
--    uLong disk_num_start;       /* disk number start               2 bytes */
--    uLong internal_fa;          /* internal file attributes        2 bytes */
--    uLong external_fa;          /* external file attributes        4 bytes */
--
--    tm_unz tmu_date;
--} unz_file_info64;
--
--typedef struct unz_file_info_s
--{
--    uLong version;              /* version made by                 2 bytes */
--    uLong version_needed;       /* version needed to extract       2 bytes */
--    uLong flag;                 /* general purpose bit flag        2 bytes */
--    uLong compression_method;   /* compression method              2 bytes */
--    uLong dosDate;              /* last mod file date in Dos fmt   4 bytes */
--    uLong crc;                  /* crc-32                          4 bytes */
--    uLong compressed_size;      /* compressed size                 4 bytes */
--    uLong uncompressed_size;    /* uncompressed size               4 bytes */
--    uLong size_filename;        /* filename length                 2 bytes */
--    uLong size_file_extra;      /* extra field length              2 bytes */
--    uLong size_file_comment;    /* file comment length             2 bytes */
--
--    uLong disk_num_start;       /* disk number start               2 bytes */
--    uLong internal_fa;          /* internal file attributes        2 bytes */
--    uLong external_fa;          /* external file attributes        4 bytes */
--
--    tm_unz tmu_date;
--} unz_file_info;
--
--extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
--                                                 const char* fileName2,
--                                                 int iCaseSensitivity));
--/*
--   Compare two filename (fileName1,fileName2).
--   If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
--   If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
--                                or strcasecmp)
--   If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
--    (like 1 on Unix, 2 on Windows)
--*/
--
--
--extern unzFile ZEXPORT unzOpen OF((const char *path));
--extern unzFile ZEXPORT unzOpen64 OF((const void *path));
--/*
--  Open a Zip file. path contain the full pathname (by example,
--     on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer
--     "zlib/zlib113.zip".
--     If the zipfile cannot be opened (file don't exist or in not valid), the
--       return value is NULL.
--     Else, the return value is a unzFile Handle, usable with other function
--       of this unzip package.
--     the "64" function take a const void* pointer, because the path is just the
--       value passed to the open64_file_func callback.
--     Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path
--       is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char*
--       does not describe the reality
--*/
--
--
--extern unzFile ZEXPORT unzOpen2 OF((const char *path,
--                                    zlib_filefunc_def* pzlib_filefunc_def));
--/*
--   Open a Zip file, like unzOpen, but provide a set of file low level API
--      for read/write the zip file (see ioapi.h)
--*/
--
--extern unzFile ZEXPORT unzOpen2_64 OF((const void *path,
--                                    zlib_filefunc64_def* pzlib_filefunc_def));
--/*
--   Open a Zip file, like unz64Open, but provide a set of file low level API
--      for read/write the zip file (see ioapi.h)
--*/
--
--extern int ZEXPORT unzClose OF((unzFile file));
--/*
--  Close a ZipFile opened with unzOpen.
--  If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
--    these files MUST be closed with unzCloseCurrentFile before call unzClose.
--  return UNZ_OK if there is no problem. */
--
--extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
--                                        unz_global_info *pglobal_info));
--
--extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file,
--                                        unz_global_info64 *pglobal_info));
--/*
--  Write info about the ZipFile in the *pglobal_info structure.
--  No preparation of the structure is needed
--  return UNZ_OK if there is no problem. */
--
--
--extern int ZEXPORT unzGetGlobalComment OF((unzFile file,
--                                           char *szComment,
--                                           uLong uSizeBuf));
--/*
--  Get the global comment string of the ZipFile, in the szComment buffer.
--  uSizeBuf is the size of the szComment buffer.
--  return the number of byte copied or an error code <0
--*/
--
--
--/***************************************************************************/
--/* Unzip package allow you browse the directory of the zipfile */
--
--extern int ZEXPORT unzGoToFirstFile OF((unzFile file));
--/*
--  Set the current file of the zipfile to the first file.
--  return UNZ_OK if there is no problem
--*/
--
--extern int ZEXPORT unzGoToNextFile OF((unzFile file));
--/*
--  Set the current file of the zipfile to the next file.
--  return UNZ_OK if there is no problem
--  return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
--*/
--
--extern int ZEXPORT unzLocateFile OF((unzFile file,
--                     const char *szFileName,
--                     int iCaseSensitivity));
--/*
--  Try locate the file szFileName in the zipfile.
--  For the iCaseSensitivity signification, see unzStringFileNameCompare
--
--  return value :
--  UNZ_OK if the file is found. It becomes the current file.
--  UNZ_END_OF_LIST_OF_FILE if the file is not found
--*/
--
--
--/* ****************************************** */
--/* Ryan supplied functions */
--/* unz_file_info contain information about a file in the zipfile */
--typedef struct unz_file_pos_s
--{
--    uLong pos_in_zip_directory;   /* offset in zip file directory */
--    uLong num_of_file;            /* # of file */
--} unz_file_pos;
--
--extern int ZEXPORT unzGetFilePos(
--    unzFile file,
--    unz_file_pos* file_pos);
--
--extern int ZEXPORT unzGoToFilePos(
--    unzFile file,
--    unz_file_pos* file_pos);
--
--typedef struct unz64_file_pos_s
--{
--    ZPOS64_T pos_in_zip_directory;   /* offset in zip file directory */
--    ZPOS64_T num_of_file;            /* # of file */
--} unz64_file_pos;
--
--extern int ZEXPORT unzGetFilePos64(
--    unzFile file,
--    unz64_file_pos* file_pos);
--
--extern int ZEXPORT unzGoToFilePos64(
--    unzFile file,
--    const unz64_file_pos* file_pos);
--
--/* ****************************************** */
--
--extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file,
--                         unz_file_info64 *pfile_info,
--                         char *szFileName,
--                         uLong fileNameBufferSize,
--                         void *extraField,
--                         uLong extraFieldBufferSize,
--                         char *szComment,
--                         uLong commentBufferSize));
--
--extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
--                         unz_file_info *pfile_info,
--                         char *szFileName,
--                         uLong fileNameBufferSize,
--                         void *extraField,
--                         uLong extraFieldBufferSize,
--                         char *szComment,
--                         uLong commentBufferSize));
--/*
--  Get Info about the current file
--  if pfile_info!=NULL, the *pfile_info structure will contain somes info about
--        the current file
--  if szFileName!=NULL, the filemane string will be copied in szFileName
--            (fileNameBufferSize is the size of the buffer)
--  if extraField!=NULL, the extra field information will be copied in extraField
--            (extraFieldBufferSize is the size of the buffer).
--            This is the Central-header version of the extra field
--  if szComment!=NULL, the comment string of the file will be copied in szComment
--            (commentBufferSize is the size of the buffer)
--*/
--
--
--/** Addition for GDAL : START */
--
--extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file));
--
--/** Addition for GDAL : END */
--
--
--/***************************************************************************/
--/* for reading the content of the current zipfile, you can open it, read data
--   from it, and close it (you can close it before reading all the file)
--   */
--
--extern int ZEXPORT unzOpenCurrentFile OF((unzFile file));
--/*
--  Open for reading data the current file in the zipfile.
--  If there is no error, the return value is UNZ_OK.
--*/
--
--extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file,
--                                                  const char* password));
--/*
--  Open for reading data the current file in the zipfile.
--  password is a crypting password
--  If there is no error, the return value is UNZ_OK.
--*/
--
--extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file,
--                                           int* method,
--                                           int* level,
--                                           int raw));
--/*
--  Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
--    if raw==1
--  *method will receive method of compression, *level will receive level of
--     compression
--  note : you can set level parameter as NULL (if you did not want known level,
--         but you CANNOT set method parameter as NULL
--*/
--
--extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file,
--                                           int* method,
--                                           int* level,
--                                           int raw,
--                                           const char* password));
--/*
--  Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
--    if raw==1
--  *method will receive method of compression, *level will receive level of
--     compression
--  note : you can set level parameter as NULL (if you did not want known level,
--         but you CANNOT set method parameter as NULL
--*/
--
--
--extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
--/*
--  Close the file in zip opened with unzOpenCurrentFile
--  Return UNZ_CRCERROR if all the file was read but the CRC is not good
--*/
--
--extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
--                      voidp buf,
--                      unsigned len));
--/*
--  Read bytes from the current file (opened by unzOpenCurrentFile)
--  buf contain buffer where data must be copied
--  len the size of buf.
--
--  return the number of byte copied if somes bytes are copied
--  return 0 if the end of file was reached
--  return <0 with error code if there is an error
--    (UNZ_ERRNO for IO error, or zLib error for uncompress error)
--*/
--
--extern z_off_t ZEXPORT unztell OF((unzFile file));
--
--extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file));
--/*
--  Give the current position in uncompressed data
--*/
--
--extern int ZEXPORT unzeof OF((unzFile file));
--/*
--  return 1 if the end of file was reached, 0 elsewhere
--*/
--
--extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
--                                             voidp buf,
--                                             unsigned len));
--/*
--  Read extra field from the current file (opened by unzOpenCurrentFile)
--  This is the local-header version of the extra field (sometimes, there is
--    more info in the local-header version than in the central-header)
--
--  if buf==NULL, it return the size of the local extra field
--
--  if buf!=NULL, len is the size of the buffer, the extra header is copied in
--    buf.
--  the return value is the number of bytes copied in buf, or (if <0)
--    the error code
--*/
--
--/***************************************************************************/
--
--/* Get the current file offset */
--extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file);
--extern uLong ZEXPORT unzGetOffset (unzFile file);
--
--/* Set the current file offset */
--extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos);
--extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
--
--
--
--#ifdef __cplusplus
--}
--#endif
--
--#endif /* _unz64_H */
diff --cc zlib/contrib/minizip/zip.c
index 44e88a9cb9898d8c7ba8a9671d259286dd4b2f79,44e88a9cb9898d8c7ba8a9671d259286dd4b2f79..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2007 -1,2007 +1,0 @@@
--/* zip.c -- IO on .zip files using zlib
--   Version 1.1, February 14h, 2010
--   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications for Zip64 support
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--         Changes
--   Oct-2009 - Mathias Svensson - Remove old C style function prototypes
--   Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives
--   Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions.
--   Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data
--                                 It is used when recreting zip archive with RAW when deleting items from a zip.
--                                 ZIP64 data is automatically added to items that needs it, and existing ZIP64 data need to be removed.
--   Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required)
--   Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer
--
--*/
--
--
--#include <stdio.h>
--#include <stdlib.h>
--#include <string.h>
--#include <time.h>
--#include "zlib.h"
--#include "zip.h"
--
--#ifdef STDC
--#  include <stddef.h>
--#  include <string.h>
--#  include <stdlib.h>
--#endif
--#ifdef NO_ERRNO_H
--    extern int errno;
--#else
--#   include <errno.h>
--#endif
--
--
--#ifndef local
--#  define local static
--#endif
--/* compile with -Dlocal if your debugger can't find static symbols */
--
--#ifndef VERSIONMADEBY
--# define VERSIONMADEBY   (0x0) /* platform depedent */
--#endif
--
--#ifndef Z_BUFSIZE
--#define Z_BUFSIZE (64*1024) //(16384)
--#endif
--
--#ifndef Z_MAXFILENAMEINZIP
--#define Z_MAXFILENAMEINZIP (256)
--#endif
--
--#ifndef ALLOC
--# define ALLOC(size) (malloc(size))
--#endif
--#ifndef TRYFREE
--# define TRYFREE(p) {if (p) free(p);}
--#endif
--
--/*
--#define SIZECENTRALDIRITEM (0x2e)
--#define SIZEZIPLOCALHEADER (0x1e)
--*/
--
--/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
--
--
--// NOT sure that this work on ALL platform
--#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32))
--
--#ifndef SEEK_CUR
--#define SEEK_CUR    1
--#endif
--
--#ifndef SEEK_END
--#define SEEK_END    2
--#endif
--
--#ifndef SEEK_SET
--#define SEEK_SET    0
--#endif
--
--#ifndef DEF_MEM_LEVEL
--#if MAX_MEM_LEVEL >= 8
--#  define DEF_MEM_LEVEL 8
--#else
--#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
--#endif
--#endif
--const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
--
--
--#define SIZEDATA_INDATABLOCK (4096-(4*4))
--
--#define LOCALHEADERMAGIC    (0x04034b50)
--#define CENTRALHEADERMAGIC  (0x02014b50)
--#define ENDHEADERMAGIC      (0x06054b50)
--#define ZIP64ENDHEADERMAGIC      (0x6064b50)
--#define ZIP64ENDLOCHEADERMAGIC   (0x7064b50)
--
--#define FLAG_LOCALHEADER_OFFSET (0x06)
--#define CRC_LOCALHEADER_OFFSET  (0x0e)
--
--#define SIZECENTRALHEADER (0x2e) /* 46 */
--
--typedef struct linkedlist_datablock_internal_s
--{
--  struct linkedlist_datablock_internal_s* next_datablock;
--  uLong  avail_in_this_block;
--  uLong  filled_in_this_block;
--  uLong  unused; /* for future use and alignment */
--  unsigned char data[SIZEDATA_INDATABLOCK];
--} linkedlist_datablock_internal;
--
--typedef struct linkedlist_data_s
--{
--    linkedlist_datablock_internal* first_block;
--    linkedlist_datablock_internal* last_block;
--} linkedlist_data;
--
--
--typedef struct
--{
--    z_stream stream;            /* zLib stream structure for inflate */
--#ifdef HAVE_BZIP2
--    bz_stream bstream;          /* bzLib stream structure for bziped */
--#endif
--
--    int  stream_initialised;    /* 1 is stream is initialised */
--    uInt pos_in_buffered_data;  /* last written byte in buffered_data */
--
--    ZPOS64_T pos_local_header;     /* offset of the local header of the file
--                                     currenty writing */
--    char* central_header;       /* central header data for the current file */
--    uLong size_centralExtra;
--    uLong size_centralheader;   /* size of the central header for cur file */
--    uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */
--    uLong flag;                 /* flag of the file currently writing */
--
--    int  method;                /* compression method of file currenty wr.*/
--    int  raw;                   /* 1 for directly writing raw data */
--    Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/
--    uLong dosDate;
--    uLong crc32;
--    int  encrypt;
--    int  zip64;               /* Add ZIP64 extened information in the extra field */
--    ZPOS64_T pos_zip64extrainfo;
--    ZPOS64_T totalCompressedData;
--    ZPOS64_T totalUncompressedData;
--#ifndef NOCRYPT
--    unsigned long keys[3];     /* keys defining the pseudo-random sequence */
--    const z_crc_t* pcrc_32_tab;
--    int crypt_header_size;
--#endif
--} curfile64_info;
--
--typedef struct
--{
--    zlib_filefunc64_32_def z_filefunc;
--    voidpf filestream;        /* io structore of the zipfile */
--    linkedlist_data central_dir;/* datablock with central dir in construction*/
--    int  in_opened_file_inzip;  /* 1 if a file in the zip is currently writ.*/
--    curfile64_info ci;            /* info on the file curretly writing */
--
--    ZPOS64_T begin_pos;            /* position of the beginning of the zipfile */
--    ZPOS64_T add_position_when_writing_offset;
--    ZPOS64_T number_entry;
--
--#ifndef NO_ADDFILEINEXISTINGZIP
--    char *globalcomment;
--#endif
--
--} zip64_internal;
--
--
--#ifndef NOCRYPT
--#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED
--#include "crypt.h"
--#endif
--
--local linkedlist_datablock_internal* allocate_new_datablock()
--{
--    linkedlist_datablock_internal* ldi;
--    ldi = (linkedlist_datablock_internal*)
--                 ALLOC(sizeof(linkedlist_datablock_internal));
--    if (ldi!=NULL)
--    {
--        ldi->next_datablock = NULL ;
--        ldi->filled_in_this_block = 0 ;
--        ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ;
--    }
--    return ldi;
--}
--
--local void free_datablock(linkedlist_datablock_internal* ldi)
--{
--    while (ldi!=NULL)
--    {
--        linkedlist_datablock_internal* ldinext = ldi->next_datablock;
--        TRYFREE(ldi);
--        ldi = ldinext;
--    }
--}
--
--local void init_linkedlist(linkedlist_data* ll)
--{
--    ll->first_block = ll->last_block = NULL;
--}
--
--local void free_linkedlist(linkedlist_data* ll)
--{
--    free_datablock(ll->first_block);
--    ll->first_block = ll->last_block = NULL;
--}
--
--
--local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len)
--{
--    linkedlist_datablock_internal* ldi;
--    const unsigned char* from_copy;
--
--    if (ll==NULL)
--        return ZIP_INTERNALERROR;
--
--    if (ll->last_block == NULL)
--    {
--        ll->first_block = ll->last_block = allocate_new_datablock();
--        if (ll->first_block == NULL)
--            return ZIP_INTERNALERROR;
--    }
--
--    ldi = ll->last_block;
--    from_copy = (unsigned char*)buf;
--
--    while (len>0)
--    {
--        uInt copy_this;
--        uInt i;
--        unsigned char* to_copy;
--
--        if (ldi->avail_in_this_block==0)
--        {
--            ldi->next_datablock = allocate_new_datablock();
--            if (ldi->next_datablock == NULL)
--                return ZIP_INTERNALERROR;
--            ldi = ldi->next_datablock ;
--            ll->last_block = ldi;
--        }
--
--        if (ldi->avail_in_this_block < len)
--            copy_this = (uInt)ldi->avail_in_this_block;
--        else
--            copy_this = (uInt)len;
--
--        to_copy = &(ldi->data[ldi->filled_in_this_block]);
--
--        for (i=0;i<copy_this;i++)
--            *(to_copy+i)=*(from_copy+i);
--
--        ldi->filled_in_this_block += copy_this;
--        ldi->avail_in_this_block -= copy_this;
--        from_copy += copy_this ;
--        len -= copy_this;
--    }
--    return ZIP_OK;
--}
--
--
--
--/****************************************************************************/
--
--#ifndef NO_ADDFILEINEXISTINGZIP
--/* ===========================================================================
--   Inputs a long in LSB order to the given file
--   nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T)
--*/
--
--local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte));
--local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)
--{
--    unsigned char buf[8];
--    int n;
--    for (n = 0; n < nbByte; n++)
--    {
--        buf[n] = (unsigned char)(x & 0xff);
--        x >>= 8;
--    }
--    if (x != 0)
--      {     /* data overflow - hack for ZIP64 (X Roche) */
--      for (n = 0; n < nbByte; n++)
--        {
--          buf[n] = 0xff;
--        }
--      }
--
--    if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte)
--        return ZIP_ERRNO;
--    else
--        return ZIP_OK;
--}
--
--local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte));
--local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte)
--{
--    unsigned char* buf=(unsigned char*)dest;
--    int n;
--    for (n = 0; n < nbByte; n++) {
--        buf[n] = (unsigned char)(x & 0xff);
--        x >>= 8;
--    }
--
--    if (x != 0)
--    {     /* data overflow - hack for ZIP64 */
--       for (n = 0; n < nbByte; n++)
--       {
--          buf[n] = 0xff;
--       }
--    }
--}
--
--/****************************************************************************/
--
--
--local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm)
--{
--    uLong year = (uLong)ptm->tm_year;
--    if (year>=1980)
--        year-=1980;
--    else if (year>=80)
--        year-=80;
--    return
--      (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) |
--        ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour));
--}
--
--
--/****************************************************************************/
--
--local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi));
--
--local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi)
--{
--    unsigned char c;
--    int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1);
--    if (err==1)
--    {
--        *pi = (int)c;
--        return ZIP_OK;
--    }
--    else
--    {
--        if (ZERROR64(*pzlib_filefunc_def,filestream))
--            return ZIP_ERRNO;
--        else
--            return ZIP_EOF;
--    }
--}
--
--
--/* ===========================================================================
--   Reads a long in LSB order from the given gz_stream. Sets
--*/
--local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
--
--local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
--{
--    uLong x ;
--    int i = 0;
--    int err;
--
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x = (uLong)i;
--
--    if (err==ZIP_OK)
--        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x += ((uLong)i)<<8;
--
--    if (err==ZIP_OK)
--        *pX = x;
--    else
--        *pX = 0;
--    return err;
--}
--
--local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
--
--local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
--{
--    uLong x ;
--    int i = 0;
--    int err;
--
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x = (uLong)i;
--
--    if (err==ZIP_OK)
--        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x += ((uLong)i)<<8;
--
--    if (err==ZIP_OK)
--        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x += ((uLong)i)<<16;
--
--    if (err==ZIP_OK)
--        err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--    x += ((uLong)i)<<24;
--
--    if (err==ZIP_OK)
--        *pX = x;
--    else
--        *pX = 0;
--    return err;
--}
--
--local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX));
--
--
--local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)
--{
--  ZPOS64_T x;
--  int i = 0;
--  int err;
--
--  err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x = (ZPOS64_T)i;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<8;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<16;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<24;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<32;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<40;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<48;
--
--  if (err==ZIP_OK)
--    err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
--  x += ((ZPOS64_T)i)<<56;
--
--  if (err==ZIP_OK)
--    *pX = x;
--  else
--    *pX = 0;
--
--  return err;
--}
--
--#ifndef BUFREADCOMMENT
--#define BUFREADCOMMENT (0x400)
--#endif
--/*
--  Locate the Central directory of a zipfile (at the end, just before
--    the global comment)
--*/
--local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
--
--local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
--{
--  unsigned char* buf;
--  ZPOS64_T uSizeFile;
--  ZPOS64_T uBackRead;
--  ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
--  ZPOS64_T uPosFound=0;
--
--  if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
--    return 0;
--
--
--  uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
--
--  if (uMaxBack>uSizeFile)
--    uMaxBack = uSizeFile;
--
--  buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
--  if (buf==NULL)
--    return 0;
--
--  uBackRead = 4;
--  while (uBackRead<uMaxBack)
--  {
--    uLong uReadSize;
--    ZPOS64_T uReadPos ;
--    int i;
--    if (uBackRead+BUFREADCOMMENT>uMaxBack)
--      uBackRead = uMaxBack;
--    else
--      uBackRead+=BUFREADCOMMENT;
--    uReadPos = uSizeFile-uBackRead ;
--
--    uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
--      (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
--    if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--      break;
--
--    if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
--      break;
--
--    for (i=(int)uReadSize-3; (i--)>0;)
--      if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
--        ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
--      {
--        uPosFound = uReadPos+i;
--        break;
--      }
--
--      if (uPosFound!=0)
--        break;
--  }
--  TRYFREE(buf);
--  return uPosFound;
--}
--
--/*
--Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before
--the global comment)
--*/
--local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
--
--local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
--{
--  unsigned char* buf;
--  ZPOS64_T uSizeFile;
--  ZPOS64_T uBackRead;
--  ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
--  ZPOS64_T uPosFound=0;
--  uLong uL;
--  ZPOS64_T relativeOffset;
--
--  if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
--    return 0;
--
--  uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
--
--  if (uMaxBack>uSizeFile)
--    uMaxBack = uSizeFile;
--
--  buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
--  if (buf==NULL)
--    return 0;
--
--  uBackRead = 4;
--  while (uBackRead<uMaxBack)
--  {
--    uLong uReadSize;
--    ZPOS64_T uReadPos;
--    int i;
--    if (uBackRead+BUFREADCOMMENT>uMaxBack)
--      uBackRead = uMaxBack;
--    else
--      uBackRead+=BUFREADCOMMENT;
--    uReadPos = uSizeFile-uBackRead ;
--
--    uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
--      (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
--    if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--      break;
--
--    if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
--      break;
--
--    for (i=(int)uReadSize-3; (i--)>0;)
--    {
--      // Signature "0x07064b50" Zip64 end of central directory locater
--      if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07))
--      {
--        uPosFound = uReadPos+i;
--        break;
--      }
--    }
--
--      if (uPosFound!=0)
--        break;
--  }
--
--  TRYFREE(buf);
--  if (uPosFound == 0)
--    return 0;
--
--  /* Zip64 end of central directory locator */
--  if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0)
--    return 0;
--
--  /* the signature, already checked */
--  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
--    return 0;
--
--  /* number of the disk with the start of the zip64 end of  central directory */
--  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
--    return 0;
--  if (uL != 0)
--    return 0;
--
--  /* relative offset of the zip64 end of central directory record */
--  if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK)
--    return 0;
--
--  /* total number of disks */
--  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
--    return 0;
--  if (uL != 1)
--    return 0;
--
--  /* Goto Zip64 end of central directory record */
--  if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0)
--    return 0;
--
--  /* the signature */
--  if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
--    return 0;
--
--  if (uL != 0x06064b50) // signature of 'Zip64 end of central directory'
--    return 0;
--
--  return relativeOffset;
--}
--
--int LoadCentralDirectoryRecord(zip64_internal* pziinit)
--{
--  int err=ZIP_OK;
--  ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
--
--  ZPOS64_T size_central_dir;     /* size of the central directory  */
--  ZPOS64_T offset_central_dir;   /* offset of start of central directory */
--  ZPOS64_T central_pos;
--  uLong uL;
--
--  uLong number_disk;          /* number of the current dist, used for
--                              spaning ZIP, unsupported, always 0*/
--  uLong number_disk_with_CD;  /* number the the disk with central dir, used
--                              for spaning ZIP, unsupported, always 0*/
--  ZPOS64_T number_entry;
--  ZPOS64_T number_entry_CD;      /* total number of entries in
--                                the central dir
--                                (same than number_entry on nospan) */
--  uLong VersionMadeBy;
--  uLong VersionNeeded;
--  uLong size_comment;
--
--  int hasZIP64Record = 0;
--
--  // check first if we find a ZIP64 record
--  central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream);
--  if(central_pos > 0)
--  {
--    hasZIP64Record = 1;
--  }
--  else if(central_pos == 0)
--  {
--    central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream);
--  }
--
--/* disable to allow appending to empty ZIP archive
--        if (central_pos==0)
--            err=ZIP_ERRNO;
--*/
--
--  if(hasZIP64Record)
--  {
--    ZPOS64_T sizeEndOfCentralDirectory;
--    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0)
--      err=ZIP_ERRNO;
--
--    /* the signature, already checked */
--    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* size of zip64 end of central directory record */
--    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* version made by */
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* version needed to extract */
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* number of this disk */
--    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* number of the disk with the start of the central directory */
--    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* total number of entries in the central directory on this disk */
--    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* total number of entries in the central directory */
--    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
--      err=ZIP_BADZIPFILE;
--
--    /* size of the central directory */
--    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* offset of start of central directory with respect to the
--    starting disk number */
--    if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    // TODO..
--    // read the comment from the standard central header.
--    size_comment = 0;
--  }
--  else
--  {
--    // Read End of central Directory info
--    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
--      err=ZIP_ERRNO;
--
--    /* the signature, already checked */
--    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* number of this disk */
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* number of the disk with the start of the central directory */
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
--      err=ZIP_ERRNO;
--
--    /* total number of entries in the central dir on this disk */
--    number_entry = 0;
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
--      err=ZIP_ERRNO;
--    else
--      number_entry = uL;
--
--    /* total number of entries in the central dir */
--    number_entry_CD = 0;
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
--      err=ZIP_ERRNO;
--    else
--      number_entry_CD = uL;
--
--    if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
--      err=ZIP_BADZIPFILE;
--
--    /* size of the central directory */
--    size_central_dir = 0;
--    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
--      err=ZIP_ERRNO;
--    else
--      size_central_dir = uL;
--
--    /* offset of start of central directory with respect to the starting disk number */
--    offset_central_dir = 0;
--    if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
--      err=ZIP_ERRNO;
--    else
--      offset_central_dir = uL;
--
--
--    /* zipfile global comment length */
--    if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK)
--      err=ZIP_ERRNO;
--  }
--
--  if ((central_pos<offset_central_dir+size_central_dir) &&
--    (err==ZIP_OK))
--    err=ZIP_BADZIPFILE;
--
--  if (err!=ZIP_OK)
--  {
--    ZCLOSE64(pziinit->z_filefunc, pziinit->filestream);
--    return ZIP_ERRNO;
--  }
--
--  if (size_comment>0)
--  {
--    pziinit->globalcomment = (char*)ALLOC(size_comment+1);
--    if (pziinit->globalcomment)
--    {
--      size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment);
--      pziinit->globalcomment[size_comment]=0;
--    }
--  }
--
--  byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir);
--  pziinit->add_position_when_writing_offset = byte_before_the_zipfile;
--
--  {
--    ZPOS64_T size_central_dir_to_read = size_central_dir;
--    size_t buf_size = SIZEDATA_INDATABLOCK;
--    void* buf_read = (void*)ALLOC(buf_size);
--    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0)
--      err=ZIP_ERRNO;
--
--    while ((size_central_dir_to_read>0) && (err==ZIP_OK))
--    {
--      ZPOS64_T read_this = SIZEDATA_INDATABLOCK;
--      if (read_this > size_central_dir_to_read)
--        read_this = size_central_dir_to_read;
--
--      if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this)
--        err=ZIP_ERRNO;
--
--      if (err==ZIP_OK)
--        err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this);
--
--      size_central_dir_to_read-=read_this;
--    }
--    TRYFREE(buf_read);
--  }
--  pziinit->begin_pos = byte_before_the_zipfile;
--  pziinit->number_entry = number_entry_CD;
--
--  if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0)
--    err=ZIP_ERRNO;
--
--  return err;
--}
--
--
--#endif /* !NO_ADDFILEINEXISTINGZIP*/
--
--
--/************************************************************/
--extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def)
--{
--    zip64_internal ziinit;
--    zip64_internal* zi;
--    int err=ZIP_OK;
--
--    ziinit.z_filefunc.zseek32_file = NULL;
--    ziinit.z_filefunc.ztell32_file = NULL;
--    if (pzlib_filefunc64_32_def==NULL)
--        fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64);
--    else
--        ziinit.z_filefunc = *pzlib_filefunc64_32_def;
--
--    ziinit.filestream = ZOPEN64(ziinit.z_filefunc,
--                  pathname,
--                  (append == APPEND_STATUS_CREATE) ?
--                  (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) :
--                    (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING));
--
--    if (ziinit.filestream == NULL)
--        return NULL;
--
--    if (append == APPEND_STATUS_CREATEAFTER)
--        ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END);
--
--    ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream);
--    ziinit.in_opened_file_inzip = 0;
--    ziinit.ci.stream_initialised = 0;
--    ziinit.number_entry = 0;
--    ziinit.add_position_when_writing_offset = 0;
--    init_linkedlist(&(ziinit.central_dir));
--
--
--
--    zi = (zip64_internal*)ALLOC(sizeof(zip64_internal));
--    if (zi==NULL)
--    {
--        ZCLOSE64(ziinit.z_filefunc,ziinit.filestream);
--        return NULL;
--    }
--
--    /* now we add file in a zipfile */
--#    ifndef NO_ADDFILEINEXISTINGZIP
--    ziinit.globalcomment = NULL;
--    if (append == APPEND_STATUS_ADDINZIP)
--    {
--      // Read and Cache Central Directory Records
--      err = LoadCentralDirectoryRecord(&ziinit);
--    }
--
--    if (globalcomment)
--    {
--      *globalcomment = ziinit.globalcomment;
--    }
--#    endif /* !NO_ADDFILEINEXISTINGZIP*/
--
--    if (err != ZIP_OK)
--    {
--#    ifndef NO_ADDFILEINEXISTINGZIP
--        TRYFREE(ziinit.globalcomment);
--#    endif /* !NO_ADDFILEINEXISTINGZIP*/
--        TRYFREE(zi);
--        return NULL;
--    }
--    else
--    {
--        *zi = ziinit;
--        return (zipFile)zi;
--    }
--}
--
--extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def)
--{
--    if (pzlib_filefunc32_def != NULL)
--    {
--        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
--        fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def);
--        return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
--    }
--    else
--        return zipOpen3(pathname, append, globalcomment, NULL);
--}
--
--extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def)
--{
--    if (pzlib_filefunc_def != NULL)
--    {
--        zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
--        zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def;
--        zlib_filefunc64_32_def_fill.ztell32_file = NULL;
--        zlib_filefunc64_32_def_fill.zseek32_file = NULL;
--        return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
--    }
--    else
--        return zipOpen3(pathname, append, globalcomment, NULL);
--}
--
--
--
--extern zipFile ZEXPORT zipOpen (const char* pathname, int append)
--{
--    return zipOpen3((const void*)pathname,append,NULL,NULL);
--}
--
--extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append)
--{
--    return zipOpen3(pathname,append,NULL,NULL);
--}
--
--int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local)
--{
--  /* write the local header */
--  int err;
--  uInt size_filename = (uInt)strlen(filename);
--  uInt size_extrafield = size_extrafield_local;
--
--  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4);
--
--  if (err==ZIP_OK)
--  {
--    if(zi->ci.zip64)
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */
--    else
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */
--  }
--
--  if (err==ZIP_OK)
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2);
--
--  if (err==ZIP_OK)
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2);
--
--  if (err==ZIP_OK)
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4);
--
--  // CRC / Compressed size / Uncompressed size will be filled in later and rewritten later
--  if (err==ZIP_OK)
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */
--  if (err==ZIP_OK)
--  {
--    if(zi->ci.zip64)
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */
--    else
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */
--  }
--  if (err==ZIP_OK)
--  {
--    if(zi->ci.zip64)
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */
--    else
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */
--  }
--
--  if (err==ZIP_OK)
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2);
--
--  if(zi->ci.zip64)
--  {
--    size_extrafield += 20;
--  }
--
--  if (err==ZIP_OK)
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2);
--
--  if ((err==ZIP_OK) && (size_filename > 0))
--  {
--    if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename)
--      err = ZIP_ERRNO;
--  }
--
--  if ((err==ZIP_OK) && (size_extrafield_local > 0))
--  {
--    if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local)
--      err = ZIP_ERRNO;
--  }
--
--
--  if ((err==ZIP_OK) && (zi->ci.zip64))
--  {
--      // write the Zip64 extended info
--      short HeaderID = 1;
--      short DataSize = 16;
--      ZPOS64_T CompressedSize = 0;
--      ZPOS64_T UncompressedSize = 0;
--
--      // Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file)
--      zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream);
--
--      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2);
--      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2);
--
--      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8);
--      err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8);
--  }
--
--  return err;
--}
--
--/*
-- NOTE.
-- When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped
-- before calling this function it can be done with zipRemoveExtraInfoBlock
--
-- It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize
-- unnecessary allocations.
-- */
--extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                         const void* extrafield_local, uInt size_extrafield_local,
--                                         const void* extrafield_global, uInt size_extrafield_global,
--                                         const char* comment, int method, int level, int raw,
--                                         int windowBits,int memLevel, int strategy,
--                                         const char* password, uLong crcForCrypting,
--                                         uLong versionMadeBy, uLong flagBase, int zip64)
--{
--    zip64_internal* zi;
--    uInt size_filename;
--    uInt size_comment;
--    uInt i;
--    int err = ZIP_OK;
--
--#    ifdef NOCRYPT
--    (crcForCrypting);
--    if (password != NULL)
--        return ZIP_PARAMERROR;
--#    endif
--
--    if (file == NULL)
--        return ZIP_PARAMERROR;
--
--#ifdef HAVE_BZIP2
--    if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED))
--      return ZIP_PARAMERROR;
--#else
--    if ((method!=0) && (method!=Z_DEFLATED))
--      return ZIP_PARAMERROR;
--#endif
--
--    zi = (zip64_internal*)file;
--
--    if (zi->in_opened_file_inzip == 1)
--    {
--        err = zipCloseFileInZip (file);
--        if (err != ZIP_OK)
--            return err;
--    }
--
--    if (filename==NULL)
--        filename="-";
--
--    if (comment==NULL)
--        size_comment = 0;
--    else
--        size_comment = (uInt)strlen(comment);
--
--    size_filename = (uInt)strlen(filename);
--
--    if (zipfi == NULL)
--        zi->ci.dosDate = 0;
--    else
--    {
--        if (zipfi->dosDate != 0)
--            zi->ci.dosDate = zipfi->dosDate;
--        else
--          zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date);
--    }
--
--    zi->ci.flag = flagBase;
--    if ((level==8) || (level==9))
--      zi->ci.flag |= 2;
--    if (level==2)
--      zi->ci.flag |= 4;
--    if (level==1)
--      zi->ci.flag |= 6;
--    if (password != NULL)
--      zi->ci.flag |= 1;
--
--    zi->ci.crc32 = 0;
--    zi->ci.method = method;
--    zi->ci.encrypt = 0;
--    zi->ci.stream_initialised = 0;
--    zi->ci.pos_in_buffered_data = 0;
--    zi->ci.raw = raw;
--    zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream);
--
--    zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment;
--    zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data
--
--    zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree);
--
--    zi->ci.size_centralExtra = size_extrafield_global;
--    zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4);
--    /* version info */
--    zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4);
--    zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/
--    zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/
--    zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/
--    zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2);
--    zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/
--
--    if (zipfi==NULL)
--        zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2);
--    else
--        zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2);
--
--    if (zipfi==NULL)
--        zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4);
--    else
--        zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);
--
--    if(zi->ci.pos_local_header >= 0xffffffff)
--      zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4);
--    else
--      zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writing_offset,4);
--
--    for (i=0;i<size_filename;i++)
--        *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i);
--
--    for (i=0;i<size_extrafield_global;i++)
--        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) =
--              *(((const char*)extrafield_global)+i);
--
--    for (i=0;i<size_comment;i++)
--        *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+
--              size_extrafield_global+i) = *(comment+i);
--    if (zi->ci.central_header == NULL)
--        return ZIP_INTERNALERROR;
--
--    zi->ci.zip64 = zip64;
--    zi->ci.totalCompressedData = 0;
--    zi->ci.totalUncompressedData = 0;
--    zi->ci.pos_zip64extrainfo = 0;
--
--    err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local);
--
--#ifdef HAVE_BZIP2
--    zi->ci.bstream.avail_in = (uInt)0;
--    zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
--    zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
--    zi->ci.bstream.total_in_hi32 = 0;
--    zi->ci.bstream.total_in_lo32 = 0;
--    zi->ci.bstream.total_out_hi32 = 0;
--    zi->ci.bstream.total_out_lo32 = 0;
--#endif
--
--    zi->ci.stream.avail_in = (uInt)0;
--    zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
--    zi->ci.stream.next_out = zi->ci.buffered_data;
--    zi->ci.stream.total_in = 0;
--    zi->ci.stream.total_out = 0;
--    zi->ci.stream.data_type = Z_BINARY;
--
--#ifdef HAVE_BZIP2
--    if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
--#else
--    if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
--#endif
--    {
--        if(zi->ci.method == Z_DEFLATED)
--        {
--          zi->ci.stream.zalloc = (alloc_func)0;
--          zi->ci.stream.zfree = (free_func)0;
--          zi->ci.stream.opaque = (voidpf)0;
--
--          if (windowBits>0)
--              windowBits = -windowBits;
--
--          err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy);
--
--          if (err==Z_OK)
--              zi->ci.stream_initialised = Z_DEFLATED;
--        }
--        else if(zi->ci.method == Z_BZIP2ED)
--        {
--#ifdef HAVE_BZIP2
--            // Init BZip stuff here
--          zi->ci.bstream.bzalloc = 0;
--          zi->ci.bstream.bzfree = 0;
--          zi->ci.bstream.opaque = (voidpf)0;
--
--          err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35);
--          if(err == BZ_OK)
--            zi->ci.stream_initialised = Z_BZIP2ED;
--#endif
--        }
--
--    }
--
--#    ifndef NOCRYPT
--    zi->ci.crypt_header_size = 0;
--    if ((err==Z_OK) && (password != NULL))
--    {
--        unsigned char bufHead[RAND_HEAD_LEN];
--        unsigned int sizeHead;
--        zi->ci.encrypt = 1;
--        zi->ci.pcrc_32_tab = get_crc_table();
--        /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/
--
--        sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting);
--        zi->ci.crypt_header_size = sizeHead;
--
--        if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead)
--                err = ZIP_ERRNO;
--    }
--#    endif
--
--    if (err==Z_OK)
--        zi->in_opened_file_inzip = 1;
--    return err;
--}
--
--extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                         const void* extrafield_local, uInt size_extrafield_local,
--                                         const void* extrafield_global, uInt size_extrafield_global,
--                                         const char* comment, int method, int level, int raw,
--                                         int windowBits,int memLevel, int strategy,
--                                         const char* password, uLong crcForCrypting,
--                                         uLong versionMadeBy, uLong flagBase)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, raw,
--                                 windowBits, memLevel, strategy,
--                                 password, crcForCrypting, versionMadeBy, flagBase, 0);
--}
--
--extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                         const void* extrafield_local, uInt size_extrafield_local,
--                                         const void* extrafield_global, uInt size_extrafield_global,
--                                         const char* comment, int method, int level, int raw,
--                                         int windowBits,int memLevel, int strategy,
--                                         const char* password, uLong crcForCrypting)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, raw,
--                                 windowBits, memLevel, strategy,
--                                 password, crcForCrypting, VERSIONMADEBY, 0, 0);
--}
--
--extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                         const void* extrafield_local, uInt size_extrafield_local,
--                                         const void* extrafield_global, uInt size_extrafield_global,
--                                         const char* comment, int method, int level, int raw,
--                                         int windowBits,int memLevel, int strategy,
--                                         const char* password, uLong crcForCrypting, int zip64)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, raw,
--                                 windowBits, memLevel, strategy,
--                                 password, crcForCrypting, VERSIONMADEBY, 0, zip64);
--}
--
--extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                        const void* extrafield_local, uInt size_extrafield_local,
--                                        const void* extrafield_global, uInt size_extrafield_global,
--                                        const char* comment, int method, int level, int raw)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, raw,
--                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
--                                 NULL, 0, VERSIONMADEBY, 0, 0);
--}
--
--extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                        const void* extrafield_local, uInt size_extrafield_local,
--                                        const void* extrafield_global, uInt size_extrafield_global,
--                                        const char* comment, int method, int level, int raw, int zip64)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, raw,
--                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
--                                 NULL, 0, VERSIONMADEBY, 0, zip64);
--}
--
--extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                        const void* extrafield_local, uInt size_extrafield_local,
--                                        const void*extrafield_global, uInt size_extrafield_global,
--                                        const char* comment, int method, int level, int zip64)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, 0,
--                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
--                                 NULL, 0, VERSIONMADEBY, 0, zip64);
--}
--
--extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi,
--                                        const void* extrafield_local, uInt size_extrafield_local,
--                                        const void*extrafield_global, uInt size_extrafield_global,
--                                        const char* comment, int method, int level)
--{
--    return zipOpenNewFileInZip4_64 (file, filename, zipfi,
--                                 extrafield_local, size_extrafield_local,
--                                 extrafield_global, size_extrafield_global,
--                                 comment, method, level, 0,
--                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
--                                 NULL, 0, VERSIONMADEBY, 0, 0);
--}
--
--local int zip64FlushWriteBuffer(zip64_internal* zi)
--{
--    int err=ZIP_OK;
--
--    if (zi->ci.encrypt != 0)
--    {
--#ifndef NOCRYPT
--        uInt i;
--        int t;
--        for (i=0;i<zi->ci.pos_in_buffered_data;i++)
--            zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t);
--#endif
--    }
--
--    if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data)
--      err = ZIP_ERRNO;
--
--    zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data;
--
--#ifdef HAVE_BZIP2
--    if(zi->ci.method == Z_BZIP2ED)
--    {
--      zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32;
--      zi->ci.bstream.total_in_lo32 = 0;
--      zi->ci.bstream.total_in_hi32 = 0;
--    }
--    else
--#endif
--    {
--      zi->ci.totalUncompressedData += zi->ci.stream.total_in;
--      zi->ci.stream.total_in = 0;
--    }
--
--
--    zi->ci.pos_in_buffered_data = 0;
--
--    return err;
--}
--
--extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len)
--{
--    zip64_internal* zi;
--    int err=ZIP_OK;
--
--    if (file == NULL)
--        return ZIP_PARAMERROR;
--    zi = (zip64_internal*)file;
--
--    if (zi->in_opened_file_inzip == 0)
--        return ZIP_PARAMERROR;
--
--    zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len);
--
--#ifdef HAVE_BZIP2
--    if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw))
--    {
--      zi->ci.bstream.next_in = (void*)buf;
--      zi->ci.bstream.avail_in = len;
--      err = BZ_RUN_OK;
--
--      while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0))
--      {
--        if (zi->ci.bstream.avail_out == 0)
--        {
--          if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
--            err = ZIP_ERRNO;
--          zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
--          zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
--        }
--
--
--        if(err != BZ_RUN_OK)
--          break;
--
--        if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
--        {
--          uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32;
--//          uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32;
--          err=BZ2_bzCompress(&zi->ci.bstream,  BZ_RUN);
--
--          zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ;
--        }
--      }
--
--      if(err == BZ_RUN_OK)
--        err = ZIP_OK;
--    }
--    else
--#endif
--    {
--      zi->ci.stream.next_in = (Bytef*)buf;
--      zi->ci.stream.avail_in = len;
--
--      while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0))
--      {
--          if (zi->ci.stream.avail_out == 0)
--          {
--              if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
--                  err = ZIP_ERRNO;
--              zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
--              zi->ci.stream.next_out = zi->ci.buffered_data;
--          }
--
--
--          if(err != ZIP_OK)
--              break;
--
--          if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
--          {
--              uLong uTotalOutBefore = zi->ci.stream.total_out;
--              err=deflate(&zi->ci.stream,  Z_NO_FLUSH);
--              if(uTotalOutBefore > zi->ci.stream.total_out)
--              {
--                int bBreak = 0;
--                bBreak++;
--              }
--
--              zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
--          }
--          else
--          {
--              uInt copy_this,i;
--              if (zi->ci.stream.avail_in < zi->ci.stream.avail_out)
--                  copy_this = zi->ci.stream.avail_in;
--              else
--                  copy_this = zi->ci.stream.avail_out;
--
--              for (i = 0; i < copy_this; i++)
--                  *(((char*)zi->ci.stream.next_out)+i) =
--                      *(((const char*)zi->ci.stream.next_in)+i);
--              {
--                  zi->ci.stream.avail_in -= copy_this;
--                  zi->ci.stream.avail_out-= copy_this;
--                  zi->ci.stream.next_in+= copy_this;
--                  zi->ci.stream.next_out+= copy_this;
--                  zi->ci.stream.total_in+= copy_this;
--                  zi->ci.stream.total_out+= copy_this;
--                  zi->ci.pos_in_buffered_data += copy_this;
--              }
--          }
--      }// while(...)
--    }
--
--    return err;
--}
--
--extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32)
--{
--    return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32);
--}
--
--extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32)
--{
--    zip64_internal* zi;
--    ZPOS64_T compressed_size;
--    uLong invalidValue = 0xffffffff;
--    short datasize = 0;
--    int err=ZIP_OK;
--
--    if (file == NULL)
--        return ZIP_PARAMERROR;
--    zi = (zip64_internal*)file;
--
--    if (zi->in_opened_file_inzip == 0)
--        return ZIP_PARAMERROR;
--    zi->ci.stream.avail_in = 0;
--
--    if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
--                {
--                        while (err==ZIP_OK)
--                        {
--                                uLong uTotalOutBefore;
--                                if (zi->ci.stream.avail_out == 0)
--                                {
--                                        if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
--                                                err = ZIP_ERRNO;
--                                        zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
--                                        zi->ci.stream.next_out = zi->ci.buffered_data;
--                                }
--                                uTotalOutBefore = zi->ci.stream.total_out;
--                                err=deflate(&zi->ci.stream,  Z_FINISH);
--                                zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
--                        }
--                }
--    else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
--    {
--#ifdef HAVE_BZIP2
--      err = BZ_FINISH_OK;
--      while (err==BZ_FINISH_OK)
--      {
--        uLong uTotalOutBefore;
--        if (zi->ci.bstream.avail_out == 0)
--        {
--          if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
--            err = ZIP_ERRNO;
--          zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
--          zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
--        }
--        uTotalOutBefore = zi->ci.bstream.total_out_lo32;
--        err=BZ2_bzCompress(&zi->ci.bstream,  BZ_FINISH);
--        if(err == BZ_STREAM_END)
--          err = Z_STREAM_END;
--
--        zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore);
--      }
--
--      if(err == BZ_FINISH_OK)
--        err = ZIP_OK;
--#endif
--    }
--
--    if (err==Z_STREAM_END)
--        err=ZIP_OK; /* this is normal */
--
--    if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK))
--                {
--        if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO)
--            err = ZIP_ERRNO;
--                }
--
--    if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
--    {
--        int tmp_err = deflateEnd(&zi->ci.stream);
--        if (err == ZIP_OK)
--            err = tmp_err;
--        zi->ci.stream_initialised = 0;
--    }
--#ifdef HAVE_BZIP2
--    else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
--    {
--      int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream);
--                        if (err==ZIP_OK)
--                                err = tmperr;
--                        zi->ci.stream_initialised = 0;
--    }
--#endif
--
--    if (!zi->ci.raw)
--    {
--        crc32 = (uLong)zi->ci.crc32;
--        uncompressed_size = zi->ci.totalUncompressedData;
--    }
--    compressed_size = zi->ci.totalCompressedData;
--
--#    ifndef NOCRYPT
--    compressed_size += zi->ci.crypt_header_size;
--#    endif
--
--    // update Current Item crc and sizes,
--    if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff)
--    {
--      /*version Made by*/
--      zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2);
--      /*version needed*/
--      zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2);
--
--    }
--
--    zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/
--
--
--    if(compressed_size >= 0xffffffff)
--      zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/
--    else
--      zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/
--
--    /// set internal file attributes field
--    if (zi->ci.stream.data_type == Z_ASCII)
--        zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2);
--
--    if(uncompressed_size >= 0xffffffff)
--      zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/
--    else
--      zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/
--
--    // Add ZIP64 extra info field for uncompressed size
--    if(uncompressed_size >= 0xffffffff)
--      datasize += 8;
--
--    // Add ZIP64 extra info field for compressed size
--    if(compressed_size >= 0xffffffff)
--      datasize += 8;
--
--    // Add ZIP64 extra info field for relative offset to local file header of current file
--    if(zi->ci.pos_local_header >= 0xffffffff)
--      datasize += 8;
--
--    if(datasize > 0)
--    {
--      char* p = NULL;
--
--      if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree)
--      {
--        // we can not write more data to the buffer that we have room for.
--        return ZIP_BADZIPFILE;
--      }
--
--      p = zi->ci.central_header + zi->ci.size_centralheader;
--
--      // Add Extra Information Header for 'ZIP64 information'
--      zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID
--      p += 2;
--      zip64local_putValue_inmemory(p, datasize, 2); // DataSize
--      p += 2;
--
--      if(uncompressed_size >= 0xffffffff)
--      {
--        zip64local_putValue_inmemory(p, uncompressed_size, 8);
--        p += 8;
--      }
--
--      if(compressed_size >= 0xffffffff)
--      {
--        zip64local_putValue_inmemory(p, compressed_size, 8);
--        p += 8;
--      }
--
--      if(zi->ci.pos_local_header >= 0xffffffff)
--      {
--        zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8);
--        p += 8;
--      }
--
--      // Update how much extra free space we got in the memory buffer
--      // and increase the centralheader size so the new ZIP64 fields are included
--      // ( 4 below is the size of HeaderID and DataSize field )
--      zi->ci.size_centralExtraFree -= datasize + 4;
--      zi->ci.size_centralheader += datasize + 4;
--
--      // Update the extra info size field
--      zi->ci.size_centralExtra += datasize + 4;
--      zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2);
--    }
--
--    if (err==ZIP_OK)
--        err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader);
--
--    free(zi->ci.central_header);
--
--    if (err==ZIP_OK)
--    {
--        // Update the LocalFileHeader with the new values.
--
--        ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
--
--        if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0)
--            err = ZIP_ERRNO;
--
--        if (err==ZIP_OK)
--            err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */
--
--        if(uncompressed_size >= 0xffffffff || compressed_size >= 0xffffffff )
--        {
--          if(zi->ci.pos_zip64extrainfo > 0)
--          {
--            // Update the size in the ZIP64 extended field.
--            if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0)
--              err = ZIP_ERRNO;
--
--            if (err==ZIP_OK) /* compressed size, unknown */
--              err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8);
--
--            if (err==ZIP_OK) /* uncompressed size, unknown */
--              err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8);
--          }
--          else
--              err = ZIP_BADZIPFILE; // Caller passed zip64 = 0, so no room for zip64 info -> fatal
--        }
--        else
--        {
--          if (err==ZIP_OK) /* compressed size, unknown */
--              err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4);
--
--          if (err==ZIP_OK) /* uncompressed size, unknown */
--              err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4);
--        }
--
--        if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0)
--            err = ZIP_ERRNO;
--    }
--
--    zi->number_entry ++;
--    zi->in_opened_file_inzip = 0;
--
--    return err;
--}
--
--extern int ZEXPORT zipCloseFileInZip (zipFile file)
--{
--    return zipCloseFileInZipRaw (file,0,0);
--}
--
--int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip)
--{
--  int err = ZIP_OK;
--  ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writing_offset;
--
--  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4);
--
--  /*num disks*/
--    if (err==ZIP_OK) /* number of the disk with the start of the central directory */
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
--
--  /*relative offset*/
--    if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8);
--
--  /*total disks*/ /* Do not support spawning of disk so always say 1 here*/
--    if (err==ZIP_OK) /* number of the disk with the start of the central directory */
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4);
--
--    return err;
--}
--
--int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
--{
--  int err = ZIP_OK;
--
--  uLong Zip64DataSize = 44;
--
--  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4);
--
--  if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ?
--
--  if (err==ZIP_OK) /* version made by */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
--
--  if (err==ZIP_OK) /* version needed */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
--
--  if (err==ZIP_OK) /* number of this disk */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
--
--  if (err==ZIP_OK) /* number of the disk with the start of the central directory */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
--
--  if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
--    err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
--
--  if (err==ZIP_OK) /* total number of entries in the central dir */
--    err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
--
--  if (err==ZIP_OK) /* size of the central directory */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8);
--
--  if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
--  {
--    ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset;
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8);
--  }
--  return err;
--}
--int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
--{
--  int err = ZIP_OK;
--
--  /*signature*/
--  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4);
--
--  if (err==ZIP_OK) /* number of this disk */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
--
--  if (err==ZIP_OK) /* number of the disk with the start of the central directory */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
--
--  if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
--  {
--    {
--      if(zi->number_entry >= 0xFFFF)
--        err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
--      else
--        err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
--    }
--  }
--
--  if (err==ZIP_OK) /* total number of entries in the central dir */
--  {
--    if(zi->number_entry >= 0xFFFF)
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
--    else
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
--  }
--
--  if (err==ZIP_OK) /* size of the central directory */
--    err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4);
--
--  if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
--  {
--    ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset;
--    if(pos >= 0xffffffff)
--    {
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4);
--    }
--    else
--      err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writing_offset),4);
--  }
--
--   return err;
--}
--
--int Write_GlobalComment(zip64_internal* zi, const char* global_comment)
--{
--  int err = ZIP_OK;
--  uInt size_global_comment = 0;
--
--  if(global_comment != NULL)
--    size_global_comment = (uInt)strlen(global_comment);
--
--  err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2);
--
--  if (err == ZIP_OK && size_global_comment > 0)
--  {
--    if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment)
--      err = ZIP_ERRNO;
--  }
--  return err;
--}
--
--extern int ZEXPORT zipClose (zipFile file, const char* global_comment)
--{
--    zip64_internal* zi;
--    int err = 0;
--    uLong size_centraldir = 0;
--    ZPOS64_T centraldir_pos_inzip;
--    ZPOS64_T pos;
--
--    if (file == NULL)
--        return ZIP_PARAMERROR;
--
--    zi = (zip64_internal*)file;
--
--    if (zi->in_opened_file_inzip == 1)
--    {
--        err = zipCloseFileInZip (file);
--    }
--
--#ifndef NO_ADDFILEINEXISTINGZIP
--    if (global_comment==NULL)
--        global_comment = zi->globalcomment;
--#endif
--
--    centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
--
--    if (err==ZIP_OK)
--    {
--        linkedlist_datablock_internal* ldi = zi->central_dir.first_block;
--        while (ldi!=NULL)
--        {
--            if ((err==ZIP_OK) && (ldi->filled_in_this_block>0))
--            {
--                if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block)
--                    err = ZIP_ERRNO;
--            }
--
--            size_centraldir += ldi->filled_in_this_block;
--            ldi = ldi->next_datablock;
--        }
--    }
--    free_linkedlist(&(zi->central_dir));
--
--    pos = centraldir_pos_inzip - zi->add_position_when_writing_offset;
--    if(pos >= 0xffffffff || zi->number_entry > 0xFFFF)
--    {
--      ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream);
--      Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
--
--      Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos);
--    }
--
--    if (err==ZIP_OK)
--      err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
--
--    if(err == ZIP_OK)
--      err = Write_GlobalComment(zi, global_comment);
--
--    if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0)
--        if (err == ZIP_OK)
--            err = ZIP_ERRNO;
--
--#ifndef NO_ADDFILEINEXISTINGZIP
--    TRYFREE(zi->globalcomment);
--#endif
--    TRYFREE(zi);
--
--    return err;
--}
--
--extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader)
--{
--  char* p = pData;
--  int size = 0;
--  char* pNewHeader;
--  char* pTmp;
--  short header;
--  short dataSize;
--
--  int retVal = ZIP_OK;
--
--  if(pData == NULL || *dataLen < 4)
--    return ZIP_PARAMERROR;
--
--  pNewHeader = (char*)ALLOC(*dataLen);
--  pTmp = pNewHeader;
--
--  while(p < (pData + *dataLen))
--  {
--    header = *(short*)p;
--    dataSize = *(((short*)p)+1);
--
--    if( header == sHeader ) // Header found.
--    {
--      p += dataSize + 4; // skip it. do not copy to temp buffer
--    }
--    else
--    {
--      // Extra Info block should not be removed, So copy it to the temp buffer.
--      memcpy(pTmp, p, dataSize + 4);
--      p += dataSize + 4;
--      size += dataSize + 4;
--    }
--
--  }
--
--  if(size < *dataLen)
--  {
--    // clean old extra info block.
--    memset(pData,0, *dataLen);
--
--    // copy the new extra info block over the old
--    if(size > 0)
--      memcpy(pData, pNewHeader, size);
--
--    // set the new extra info size
--    *dataLen = size;
--
--    retVal = ZIP_OK;
--  }
--  else
--    retVal = ZIP_ERRNO;
--
--  TRYFREE(pNewHeader);
--
--  return retVal;
--}
diff --cc zlib/contrib/minizip/zip.h
index 8aaebb623430fcba7801c3502f8f94e46198ddb4,8aaebb623430fcba7801c3502f8f94e46198ddb4..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,362 -1,362 +1,0 @@@
--/* zip.h -- IO on .zip files using zlib
--   Version 1.1, February 14h, 2010
--   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
--
--         Modifications for Zip64 support
--         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
--
--         For more info read MiniZip_info.txt
--
--         ---------------------------------------------------------------------------
--
--   Condition of use and distribution are the same than zlib :
--
--  This software is provided 'as-is', without any express or implied
--  warranty.  In no event will the authors be held liable for any damages
--  arising from the use of this software.
--
--  Permission is granted to anyone to use this software for any purpose,
--  including commercial applications, and to alter it and redistribute it
--  freely, subject to the following restrictions:
--
--  1. The origin of this software must not be misrepresented; you must not
--     claim that you wrote the original software. If you use this software
--     in a product, an acknowledgment in the product documentation would be
--     appreciated but is not required.
--  2. Altered source versions must be plainly marked as such, and must not be
--     misrepresented as being the original software.
--  3. This notice may not be removed or altered from any source distribution.
--
--        ---------------------------------------------------------------------------
--
--        Changes
--
--        See header of zip.h
--
--*/
--
--#ifndef _zip12_H
--#define _zip12_H
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--//#define HAVE_BZIP2
--
--#ifndef _ZLIB_H
--#include "zlib.h"
--#endif
--
--#ifndef _ZLIBIOAPI_H
--#include "ioapi.h"
--#endif
--
--#ifdef HAVE_BZIP2
--#include "bzlib.h"
--#endif
--
--#define Z_BZIP2ED 12
--
--#if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
--/* like the STRICT of WIN32, we define a pointer that cannot be converted
--    from (void*) without cast */
--typedef struct TagzipFile__ { int unused; } zipFile__;
--typedef zipFile__ *zipFile;
--#else
--typedef voidp zipFile;
--#endif
--
--#define ZIP_OK                          (0)
--#define ZIP_EOF                         (0)
--#define ZIP_ERRNO                       (Z_ERRNO)
--#define ZIP_PARAMERROR                  (-102)
--#define ZIP_BADZIPFILE                  (-103)
--#define ZIP_INTERNALERROR               (-104)
--
--#ifndef DEF_MEM_LEVEL
--#  if MAX_MEM_LEVEL >= 8
--#    define DEF_MEM_LEVEL 8
--#  else
--#    define DEF_MEM_LEVEL  MAX_MEM_LEVEL
--#  endif
--#endif
--/* default memLevel */
--
--/* tm_zip contain date/time info */
--typedef struct tm_zip_s
--{
--    uInt tm_sec;            /* seconds after the minute - [0,59] */
--    uInt tm_min;            /* minutes after the hour - [0,59] */
--    uInt tm_hour;           /* hours since midnight - [0,23] */
--    uInt tm_mday;           /* day of the month - [1,31] */
--    uInt tm_mon;            /* months since January - [0,11] */
--    uInt tm_year;           /* years - [1980..2044] */
--} tm_zip;
--
--typedef struct
--{
--    tm_zip      tmz_date;       /* date in understandable format           */
--    uLong       dosDate;       /* if dos_date == 0, tmu_date is used      */
--/*    uLong       flag;        */   /* general purpose bit flag        2 bytes */
--
--    uLong       internal_fa;    /* internal file attributes        2 bytes */
--    uLong       external_fa;    /* external file attributes        4 bytes */
--} zip_fileinfo;
--
--typedef const char* zipcharpc;
--
--
--#define APPEND_STATUS_CREATE        (0)
--#define APPEND_STATUS_CREATEAFTER   (1)
--#define APPEND_STATUS_ADDINZIP      (2)
--
--extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
--extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append));
--/*
--  Create a zipfile.
--     pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on
--       an Unix computer "zlib/zlib113.zip".
--     if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip
--       will be created at the end of the file.
--         (useful if the file contain a self extractor code)
--     if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will
--       add files in existing zip (be sure you don't add file that doesn't exist)
--     If the zipfile cannot be opened, the return value is NULL.
--     Else, the return value is a zipFile Handle, usable with other function
--       of this zip package.
--*/
--
--/* Note : there is no delete function into a zipfile.
--   If you want delete file into a zipfile, you must open a zipfile, and create another
--   Of couse, you can use RAW reading and writing to copy the file you did not want delte
--*/
--
--extern zipFile ZEXPORT zipOpen2 OF((const char *pathname,
--                                   int append,
--                                   zipcharpc* globalcomment,
--                                   zlib_filefunc_def* pzlib_filefunc_def));
--
--extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname,
--                                   int append,
--                                   zipcharpc* globalcomment,
--                                   zlib_filefunc64_def* pzlib_filefunc_def));
--
--extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
--                       const char* filename,
--                       const zip_fileinfo* zipfi,
--                       const void* extrafield_local,
--                       uInt size_extrafield_local,
--                       const void* extrafield_global,
--                       uInt size_extrafield_global,
--                       const char* comment,
--                       int method,
--                       int level));
--
--extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file,
--                       const char* filename,
--                       const zip_fileinfo* zipfi,
--                       const void* extrafield_local,
--                       uInt size_extrafield_local,
--                       const void* extrafield_global,
--                       uInt size_extrafield_global,
--                       const char* comment,
--                       int method,
--                       int level,
--                       int zip64));
--
--/*
--  Open a file in the ZIP for writing.
--  filename : the filename in zip (if NULL, '-' without quote will be used
--  *zipfi contain supplemental information
--  if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local
--    contains the extrafield data the the local header
--  if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global
--    contains the extrafield data the the local header
--  if comment != NULL, comment contain the comment string
--  method contain the compression method (0 for store, Z_DEFLATED for deflate)
--  level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
--  zip64 is set to 1 if a zip64 extended information block should be added to the local file header.
--                    this MUST be '1' if the uncompressed size is >= 0xffffffff.
--
--*/
--
--
--extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file,
--                                            const char* filename,
--                                            const zip_fileinfo* zipfi,
--                                            const void* extrafield_local,
--                                            uInt size_extrafield_local,
--                                            const void* extrafield_global,
--                                            uInt size_extrafield_global,
--                                            const char* comment,
--                                            int method,
--                                            int level,
--                                            int raw));
--
--
--extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file,
--                                            const char* filename,
--                                            const zip_fileinfo* zipfi,
--                                            const void* extrafield_local,
--                                            uInt size_extrafield_local,
--                                            const void* extrafield_global,
--                                            uInt size_extrafield_global,
--                                            const char* comment,
--                                            int method,
--                                            int level,
--                                            int raw,
--                                            int zip64));
--/*
--  Same than zipOpenNewFileInZip, except if raw=1, we write raw file
-- */
--
--extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file,
--                                            const char* filename,
--                                            const zip_fileinfo* zipfi,
--                                            const void* extrafield_local,
--                                            uInt size_extrafield_local,
--                                            const void* extrafield_global,
--                                            uInt size_extrafield_global,
--                                            const char* comment,
--                                            int method,
--                                            int level,
--                                            int raw,
--                                            int windowBits,
--                                            int memLevel,
--                                            int strategy,
--                                            const char* password,
--                                            uLong crcForCrypting));
--
--extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file,
--                                            const char* filename,
--                                            const zip_fileinfo* zipfi,
--                                            const void* extrafield_local,
--                                            uInt size_extrafield_local,
--                                            const void* extrafield_global,
--                                            uInt size_extrafield_global,
--                                            const char* comment,
--                                            int method,
--                                            int level,
--                                            int raw,
--                                            int windowBits,
--                                            int memLevel,
--                                            int strategy,
--                                            const char* password,
--                                            uLong crcForCrypting,
--                                            int zip64
--                                            ));
--
--/*
--  Same than zipOpenNewFileInZip2, except
--    windowBits,memLevel,,strategy : see parameter strategy in deflateInit2
--    password : crypting password (NULL for no crypting)
--    crcForCrypting : crc of file to compress (needed for crypting)
-- */
--
--extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file,
--                                            const char* filename,
--                                            const zip_fileinfo* zipfi,
--                                            const void* extrafield_local,
--                                            uInt size_extrafield_local,
--                                            const void* extrafield_global,
--                                            uInt size_extrafield_global,
--                                            const char* comment,
--                                            int method,
--                                            int level,
--                                            int raw,
--                                            int windowBits,
--                                            int memLevel,
--                                            int strategy,
--                                            const char* password,
--                                            uLong crcForCrypting,
--                                            uLong versionMadeBy,
--                                            uLong flagBase
--                                            ));
--
--
--extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file,
--                                            const char* filename,
--                                            const zip_fileinfo* zipfi,
--                                            const void* extrafield_local,
--                                            uInt size_extrafield_local,
--                                            const void* extrafield_global,
--                                            uInt size_extrafield_global,
--                                            const char* comment,
--                                            int method,
--                                            int level,
--                                            int raw,
--                                            int windowBits,
--                                            int memLevel,
--                                            int strategy,
--                                            const char* password,
--                                            uLong crcForCrypting,
--                                            uLong versionMadeBy,
--                                            uLong flagBase,
--                                            int zip64
--                                            ));
--/*
--  Same than zipOpenNewFileInZip4, except
--    versionMadeBy : value for Version made by field
--    flag : value for flag field (compression level info will be added)
-- */
--
--
--extern int ZEXPORT zipWriteInFileInZip OF((zipFile file,
--                       const void* buf,
--                       unsigned len));
--/*
--  Write data in the zipfile
--*/
--
--extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
--/*
--  Close the current file in the zipfile
--*/
--
--extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
--                                            uLong uncompressed_size,
--                                            uLong crc32));
--
--extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file,
--                                            ZPOS64_T uncompressed_size,
--                                            uLong crc32));
--
--/*
--  Close the current file in the zipfile, for file opened with
--    parameter raw=1 in zipOpenNewFileInZip2
--  uncompressed_size and crc32 are value for the uncompressed size
--*/
--
--extern int ZEXPORT zipClose OF((zipFile file,
--                const char* global_comment));
--/*
--  Close the zipfile
--*/
--
--
--extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader));
--/*
--  zipRemoveExtraInfoBlock -  Added by Mathias Svensson
--
--  Remove extra information block from a extra information data for the local file header or central directory header
--
--  It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode.
--
--  0x0001 is the signature header for the ZIP64 extra information blocks
--
--  usage.
--                        Remove ZIP64 Extra information from a central director extra field data
--              zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001);
--
--                        Remove ZIP64 Extra information from a Local File Header extra field data
--        zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001);
--*/
--
--#ifdef __cplusplus
--}
--#endif
--
--#endif /* _zip64_H */
diff --cc zlib/crc32.c
index 9580440c0e6b673c43e57daab03274ebdca8f77e,9580440c0e6b673c43e57daab03274ebdca8f77e..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,442 -1,442 +1,0 @@@
--/* crc32.c -- compute the CRC-32 of a data stream
-- * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- *
-- * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
-- * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
-- * tables for updating the shift register in one step with three exclusive-ors
-- * instead of four steps with four exclusive-ors.  This results in about a
-- * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
-- */
--
--/* @(#) $Id$ */
--
--/*
--  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
--  protection on the static variables used to control the first-use generation
--  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
--  first call get_crc_table() to initialize the tables before allowing more than
--  one thread to use crc32().
--
--  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
-- */
--
--#ifdef MAKECRCH
--#  include <stdio.h>
--#  ifndef DYNAMIC_CRC_TABLE
--#    define DYNAMIC_CRC_TABLE
--#  endif /* !DYNAMIC_CRC_TABLE */
--#endif /* MAKECRCH */
--
--#include "zutil.h"      /* for STDC and FAR definitions */
--
--/* Definitions for doing the crc four data bytes at a time. */
--#if !defined(NOBYFOUR) && defined(Z_U4)
--#  define BYFOUR
--#endif
--#ifdef BYFOUR
--   local unsigned long crc32_little OF((unsigned long,
--                        const unsigned char FAR *, z_size_t));
--   local unsigned long crc32_big OF((unsigned long,
--                        const unsigned char FAR *, z_size_t));
--#  define TBLS 8
--#else
--#  define TBLS 1
--#endif /* BYFOUR */
--
--/* Local functions for crc concatenation */
--local unsigned long gf2_matrix_times OF((unsigned long *mat,
--                                         unsigned long vec));
--local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
--local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
--
--
--#ifdef DYNAMIC_CRC_TABLE
--
--local volatile int crc_table_empty = 1;
--local z_crc_t FAR crc_table[TBLS][256];
--local void make_crc_table OF((void));
--#ifdef MAKECRCH
--   local void write_table OF((FILE *, const z_crc_t FAR *));
--#endif /* MAKECRCH */
--/*
--  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
--  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
--
--  Polynomials over GF(2) are represented in binary, one bit per coefficient,
--  with the lowest powers in the most significant bit.  Then adding polynomials
--  is just exclusive-or, and multiplying a polynomial by x is a right shift by
--  one.  If we call the above polynomial p, and represent a byte as the
--  polynomial q, also with the lowest power in the most significant bit (so the
--  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
--  where a mod b means the remainder after dividing a by b.
--
--  This calculation is done using the shift-register method of multiplying and
--  taking the remainder.  The register is initialized to zero, and for each
--  incoming bit, x^32 is added mod p to the register if the bit is a one (where
--  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
--  x (which is shifting right by one and adding x^32 mod p if the bit shifted
--  out is a one).  We start with the highest power (least significant bit) of
--  q and repeat for all eight bits of q.
--
--  The first table is simply the CRC of all possible eight bit values.  This is
--  all the information needed to generate CRCs on data a byte at a time for all
--  combinations of CRC register values and incoming bytes.  The remaining tables
--  allow for word-at-a-time CRC calculation for both big-endian and little-
--  endian machines, where a word is four bytes.
--*/
--local void make_crc_table()
--{
--    z_crc_t c;
--    int n, k;
--    z_crc_t poly;                       /* polynomial exclusive-or pattern */
--    /* terms of polynomial defining this crc (except x^32): */
--    static volatile int first = 1;      /* flag to limit concurrent making */
--    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
--
--    /* See if another task is already doing this (not thread-safe, but better
--       than nothing -- significantly reduces duration of vulnerability in
--       case the advice about DYNAMIC_CRC_TABLE is ignored) */
--    if (first) {
--        first = 0;
--
--        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
--        poly = 0;
--        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
--            poly |= (z_crc_t)1 << (31 - p[n]);
--
--        /* generate a crc for every 8-bit value */
--        for (n = 0; n < 256; n++) {
--            c = (z_crc_t)n;
--            for (k = 0; k < 8; k++)
--                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
--            crc_table[0][n] = c;
--        }
--
--#ifdef BYFOUR
--        /* generate crc for each value followed by one, two, and three zeros,
--           and then the byte reversal of those as well as the first table */
--        for (n = 0; n < 256; n++) {
--            c = crc_table[0][n];
--            crc_table[4][n] = ZSWAP32(c);
--            for (k = 1; k < 4; k++) {
--                c = crc_table[0][c & 0xff] ^ (c >> 8);
--                crc_table[k][n] = c;
--                crc_table[k + 4][n] = ZSWAP32(c);
--            }
--        }
--#endif /* BYFOUR */
--
--        crc_table_empty = 0;
--    }
--    else {      /* not first */
--        /* wait for the other guy to finish (not efficient, but rare) */
--        while (crc_table_empty)
--            ;
--    }
--
--#ifdef MAKECRCH
--    /* write out CRC tables to crc32.h */
--    {
--        FILE *out;
--
--        out = fopen("crc32.h", "w");
--        if (out == NULL) return;
--        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
--        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
--        fprintf(out, "local const z_crc_t FAR ");
--        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
--        write_table(out, crc_table[0]);
--#  ifdef BYFOUR
--        fprintf(out, "#ifdef BYFOUR\n");
--        for (k = 1; k < 8; k++) {
--            fprintf(out, "  },\n  {\n");
--            write_table(out, crc_table[k]);
--        }
--        fprintf(out, "#endif\n");
--#  endif /* BYFOUR */
--        fprintf(out, "  }\n};\n");
--        fclose(out);
--    }
--#endif /* MAKECRCH */
--}
--
--#ifdef MAKECRCH
--local void write_table(out, table)
--    FILE *out;
--    const z_crc_t FAR *table;
--{
--    int n;
--
--    for (n = 0; n < 256; n++)
--        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
--                (unsigned long)(table[n]),
--                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
--}
--#endif /* MAKECRCH */
--
--#else /* !DYNAMIC_CRC_TABLE */
--/* ========================================================================
-- * Tables of CRC-32s of all single-byte values, made by make_crc_table().
-- */
--#include "crc32.h"
--#endif /* DYNAMIC_CRC_TABLE */
--
--/* =========================================================================
-- * This function can be used by asm versions of crc32()
-- */
--const z_crc_t FAR * ZEXPORT get_crc_table()
--{
--#ifdef DYNAMIC_CRC_TABLE
--    if (crc_table_empty)
--        make_crc_table();
--#endif /* DYNAMIC_CRC_TABLE */
--    return (const z_crc_t FAR *)crc_table;
--}
--
--/* ========================================================================= */
--#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
--#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
--
--/* ========================================================================= */
--unsigned long ZEXPORT crc32_z(crc, buf, len)
--    unsigned long crc;
--    const unsigned char FAR *buf;
--    z_size_t len;
--{
--    if (buf == Z_NULL) return 0UL;
--
--#ifdef DYNAMIC_CRC_TABLE
--    if (crc_table_empty)
--        make_crc_table();
--#endif /* DYNAMIC_CRC_TABLE */
--
--#ifdef BYFOUR
--    if (sizeof(void *) == sizeof(ptrdiff_t)) {
--        z_crc_t endian;
--
--        endian = 1;
--        if (*((unsigned char *)(&endian)))
--            return crc32_little(crc, buf, len);
--        else
--            return crc32_big(crc, buf, len);
--    }
--#endif /* BYFOUR */
--    crc = crc ^ 0xffffffffUL;
--    while (len >= 8) {
--        DO8;
--        len -= 8;
--    }
--    if (len) do {
--        DO1;
--    } while (--len);
--    return crc ^ 0xffffffffUL;
--}
--
--/* ========================================================================= */
--unsigned long ZEXPORT crc32(crc, buf, len)
--    unsigned long crc;
--    const unsigned char FAR *buf;
--    uInt len;
--{
--    return crc32_z(crc, buf, len);
--}
--
--#ifdef BYFOUR
--
--/*
--   This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit
--   integer pointer type. This violates the strict aliasing rule, where a
--   compiler can assume, for optimization purposes, that two pointers to
--   fundamentally different types won't ever point to the same memory. This can
--   manifest as a problem only if one of the pointers is written to. This code
--   only reads from those pointers. So long as this code remains isolated in
--   this compilation unit, there won't be a problem. For this reason, this code
--   should not be copied and pasted into a compilation unit in which other code
--   writes to the buffer that is passed to these routines.
-- */
--
--/* ========================================================================= */
--#define DOLIT4 c ^= *buf4++; \
--        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
--            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
--#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
--
--/* ========================================================================= */
--local unsigned long crc32_little(crc, buf, len)
--    unsigned long crc;
--    const unsigned char FAR *buf;
--    z_size_t len;
--{
--    register z_crc_t c;
--    register const z_crc_t FAR *buf4;
--
--    c = (z_crc_t)crc;
--    c = ~c;
--    while (len && ((ptrdiff_t)buf & 3)) {
--        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
--        len--;
--    }
--
--    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
--    while (len >= 32) {
--        DOLIT32;
--        len -= 32;
--    }
--    while (len >= 4) {
--        DOLIT4;
--        len -= 4;
--    }
--    buf = (const unsigned char FAR *)buf4;
--
--    if (len) do {
--        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
--    } while (--len);
--    c = ~c;
--    return (unsigned long)c;
--}
--
--/* ========================================================================= */
--#define DOBIG4 c ^= *buf4++; \
--        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
--            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
--#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
--
--/* ========================================================================= */
--local unsigned long crc32_big(crc, buf, len)
--    unsigned long crc;
--    const unsigned char FAR *buf;
--    z_size_t len;
--{
--    register z_crc_t c;
--    register const z_crc_t FAR *buf4;
--
--    c = ZSWAP32((z_crc_t)crc);
--    c = ~c;
--    while (len && ((ptrdiff_t)buf & 3)) {
--        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
--        len--;
--    }
--
--    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
--    while (len >= 32) {
--        DOBIG32;
--        len -= 32;
--    }
--    while (len >= 4) {
--        DOBIG4;
--        len -= 4;
--    }
--    buf = (const unsigned char FAR *)buf4;
--
--    if (len) do {
--        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
--    } while (--len);
--    c = ~c;
--    return (unsigned long)(ZSWAP32(c));
--}
--
--#endif /* BYFOUR */
--
--#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */
--
--/* ========================================================================= */
--local unsigned long gf2_matrix_times(mat, vec)
--    unsigned long *mat;
--    unsigned long vec;
--{
--    unsigned long sum;
--
--    sum = 0;
--    while (vec) {
--        if (vec & 1)
--            sum ^= *mat;
--        vec >>= 1;
--        mat++;
--    }
--    return sum;
--}
--
--/* ========================================================================= */
--local void gf2_matrix_square(square, mat)
--    unsigned long *square;
--    unsigned long *mat;
--{
--    int n;
--
--    for (n = 0; n < GF2_DIM; n++)
--        square[n] = gf2_matrix_times(mat, mat[n]);
--}
--
--/* ========================================================================= */
--local uLong crc32_combine_(crc1, crc2, len2)
--    uLong crc1;
--    uLong crc2;
--    z_off64_t len2;
--{
--    int n;
--    unsigned long row;
--    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
--    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
--
--    /* degenerate case (also disallow negative lengths) */
--    if (len2 <= 0)
--        return crc1;
--
--    /* put operator for one zero bit in odd */
--    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
--    row = 1;
--    for (n = 1; n < GF2_DIM; n++) {
--        odd[n] = row;
--        row <<= 1;
--    }
--
--    /* put operator for two zero bits in even */
--    gf2_matrix_square(even, odd);
--
--    /* put operator for four zero bits in odd */
--    gf2_matrix_square(odd, even);
--
--    /* apply len2 zeros to crc1 (first square will put the operator for one
--       zero byte, eight zero bits, in even) */
--    do {
--        /* apply zeros operator for this bit of len2 */
--        gf2_matrix_square(even, odd);
--        if (len2 & 1)
--            crc1 = gf2_matrix_times(even, crc1);
--        len2 >>= 1;
--
--        /* if no more bits set, then done */
--        if (len2 == 0)
--            break;
--
--        /* another iteration of the loop with odd and even swapped */
--        gf2_matrix_square(odd, even);
--        if (len2 & 1)
--            crc1 = gf2_matrix_times(odd, crc1);
--        len2 >>= 1;
--
--        /* if no more bits set, then done */
--    } while (len2 != 0);
--
--    /* return combined crc */
--    crc1 ^= crc2;
--    return crc1;
--}
--
--/* ========================================================================= */
--uLong ZEXPORT crc32_combine(crc1, crc2, len2)
--    uLong crc1;
--    uLong crc2;
--    z_off_t len2;
--{
--    return crc32_combine_(crc1, crc2, len2);
--}
--
--uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
--    uLong crc1;
--    uLong crc2;
--    z_off64_t len2;
--{
--    return crc32_combine_(crc1, crc2, len2);
--}
diff --cc zlib/crc32.h
index 9e0c7781025148380d130d6f7b6e590117ad3a8c,9e0c7781025148380d130d6f7b6e590117ad3a8c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,441 -1,441 +1,0 @@@
--/* crc32.h -- tables for rapid CRC calculation
-- * Generated automatically by crc32.c
-- */
--
--local const z_crc_t FAR crc_table[TBLS][256] =
--{
--  {
--    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
--    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
--    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
--    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
--    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
--    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
--    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
--    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
--    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
--    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
--    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
--    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
--    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
--    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
--    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
--    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
--    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
--    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
--    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
--    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
--    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
--    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
--    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
--    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
--    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
--    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
--    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
--    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
--    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
--    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
--    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
--    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
--    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
--    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
--    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
--    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
--    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
--    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
--    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
--    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
--    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
--    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
--    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
--    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
--    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
--    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
--    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
--    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
--    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
--    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
--    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
--    0x2d02ef8dUL
--#ifdef BYFOUR
--  },
--  {
--    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
--    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
--    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
--    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
--    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
--    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
--    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
--    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
--    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
--    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
--    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
--    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
--    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
--    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
--    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
--    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
--    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
--    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
--    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
--    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
--    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
--    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
--    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
--    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
--    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
--    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
--    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
--    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
--    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
--    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
--    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
--    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
--    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
--    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
--    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
--    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
--    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
--    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
--    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
--    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
--    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
--    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
--    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
--    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
--    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
--    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
--    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
--    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
--    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
--    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
--    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
--    0x9324fd72UL
--  },
--  {
--    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
--    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
--    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
--    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
--    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
--    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
--    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
--    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
--    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
--    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
--    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
--    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
--    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
--    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
--    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
--    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
--    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
--    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
--    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
--    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
--    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
--    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
--    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
--    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
--    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
--    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
--    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
--    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
--    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
--    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
--    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
--    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
--    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
--    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
--    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
--    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
--    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
--    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
--    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
--    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
--    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
--    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
--    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
--    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
--    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
--    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
--    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
--    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
--    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
--    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
--    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
--    0xbe9834edUL
--  },
--  {
--    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
--    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
--    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
--    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
--    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
--    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
--    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
--    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
--    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
--    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
--    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
--    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
--    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
--    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
--    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
--    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
--    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
--    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
--    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
--    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
--    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
--    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
--    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
--    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
--    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
--    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
--    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
--    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
--    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
--    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
--    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
--    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
--    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
--    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
--    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
--    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
--    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
--    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
--    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
--    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
--    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
--    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
--    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
--    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
--    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
--    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
--    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
--    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
--    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
--    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
--    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
--    0xde0506f1UL
--  },
--  {
--    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
--    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
--    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
--    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
--    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
--    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
--    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
--    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
--    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
--    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
--    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
--    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
--    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
--    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
--    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
--    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
--    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
--    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
--    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
--    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
--    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
--    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
--    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
--    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
--    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
--    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
--    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
--    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
--    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
--    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
--    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
--    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
--    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
--    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
--    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
--    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
--    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
--    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
--    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
--    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
--    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
--    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
--    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
--    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
--    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
--    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
--    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
--    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
--    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
--    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
--    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
--    0x8def022dUL
--  },
--  {
--    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
--    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
--    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
--    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
--    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
--    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
--    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
--    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
--    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
--    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
--    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
--    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
--    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
--    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
--    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
--    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
--    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
--    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
--    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
--    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
--    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
--    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
--    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
--    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
--    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
--    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
--    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
--    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
--    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
--    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
--    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
--    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
--    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
--    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
--    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
--    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
--    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
--    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
--    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
--    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
--    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
--    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
--    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
--    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
--    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
--    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
--    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
--    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
--    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
--    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
--    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
--    0x72fd2493UL
--  },
--  {
--    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
--    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
--    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
--    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
--    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
--    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
--    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
--    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
--    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
--    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
--    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
--    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
--    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
--    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
--    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
--    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
--    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
--    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
--    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
--    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
--    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
--    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
--    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
--    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
--    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
--    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
--    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
--    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
--    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
--    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
--    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
--    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
--    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
--    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
--    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
--    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
--    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
--    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
--    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
--    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
--    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
--    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
--    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
--    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
--    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
--    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
--    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
--    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
--    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
--    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
--    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
--    0xed3498beUL
--  },
--  {
--    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
--    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
--    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
--    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
--    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
--    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
--    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
--    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
--    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
--    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
--    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
--    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
--    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
--    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
--    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
--    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
--    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
--    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
--    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
--    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
--    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
--    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
--    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
--    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
--    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
--    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
--    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
--    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
--    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
--    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
--    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
--    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
--    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
--    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
--    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
--    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
--    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
--    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
--    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
--    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
--    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
--    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
--    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
--    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
--    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
--    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
--    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
--    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
--    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
--    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
--    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
--    0xf10605deUL
--#endif
--  }
--};
diff --cc zlib/deflate.c
index 1ec761448de926724c359256bbff0e8d9e851415,1ec761448de926724c359256bbff0e8d9e851415..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,2163 -1,2163 +1,0 @@@
--/* deflate.c -- compress data using the deflation algorithm
-- * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/*
-- *  ALGORITHM
-- *
-- *      The "deflation" process depends on being able to identify portions
-- *      of the input text which are identical to earlier input (within a
-- *      sliding window trailing behind the input currently being processed).
-- *
-- *      The most straightforward technique turns out to be the fastest for
-- *      most input files: try all possible matches and select the longest.
-- *      The key feature of this algorithm is that insertions into the string
-- *      dictionary are very simple and thus fast, and deletions are avoided
-- *      completely. Insertions are performed at each input character, whereas
-- *      string matches are performed only when the previous match ends. So it
-- *      is preferable to spend more time in matches to allow very fast string
-- *      insertions and avoid deletions. The matching algorithm for small
-- *      strings is inspired from that of Rabin & Karp. A brute force approach
-- *      is used to find longer strings when a small match has been found.
-- *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
-- *      (by Leonid Broukhis).
-- *         A previous version of this file used a more sophisticated algorithm
-- *      (by Fiala and Greene) which is guaranteed to run in linear amortized
-- *      time, but has a larger average cost, uses more memory and is patented.
-- *      However the F&G algorithm may be faster for some highly redundant
-- *      files if the parameter max_chain_length (described below) is too large.
-- *
-- *  ACKNOWLEDGEMENTS
-- *
-- *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
-- *      I found it in 'freeze' written by Leonid Broukhis.
-- *      Thanks to many people for bug reports and testing.
-- *
-- *  REFERENCES
-- *
-- *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
-- *      Available in http://tools.ietf.org/html/rfc1951
-- *
-- *      A description of the Rabin and Karp algorithm is given in the book
-- *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
-- *
-- *      Fiala,E.R., and Greene,D.H.
-- *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
-- *
-- */
--
--/* @(#) $Id$ */
--
--#include "deflate.h"
--
--const char deflate_copyright[] =
--   " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler ";
--/*
--  If you use the zlib library in a product, an acknowledgment is welcome
--  in the documentation of your product. If for some reason you cannot
--  include such an acknowledgment, I would appreciate that you keep this
--  copyright string in the executable of your product.
-- */
--
--/* ===========================================================================
-- *  Function prototypes.
-- */
--typedef enum {
--    need_more,      /* block not completed, need more input or more output */
--    block_done,     /* block flush performed */
--    finish_started, /* finish started, need only more output at next deflate */
--    finish_done     /* finish done, accept no more input or output */
--} block_state;
--
--typedef block_state (*compress_func) OF((deflate_state *s, int flush));
--/* Compression function. Returns the block state after the call. */
--
--local int deflateStateCheck      OF((z_streamp strm));
--local void slide_hash     OF((deflate_state *s));
--local void fill_window    OF((deflate_state *s));
--local block_state deflate_stored OF((deflate_state *s, int flush));
--local block_state deflate_fast   OF((deflate_state *s, int flush));
--#ifndef FASTEST
--local block_state deflate_slow   OF((deflate_state *s, int flush));
--#endif
--local block_state deflate_rle    OF((deflate_state *s, int flush));
--local block_state deflate_huff   OF((deflate_state *s, int flush));
--local void lm_init        OF((deflate_state *s));
--local void putShortMSB    OF((deflate_state *s, uInt b));
--local void flush_pending  OF((z_streamp strm));
--local unsigned read_buf   OF((z_streamp strm, Bytef *buf, unsigned size));
--#ifdef ASMV
--#  pragma message("Assembler code may have bugs -- use at your own risk")
--      void match_init OF((void)); /* asm code initialization */
--      uInt longest_match  OF((deflate_state *s, IPos cur_match));
--#else
--local uInt longest_match  OF((deflate_state *s, IPos cur_match));
--#endif
--
--#ifdef ZLIB_DEBUG
--local  void check_match OF((deflate_state *s, IPos start, IPos match,
--                            int length));
--#endif
--
--/* ===========================================================================
-- * Local data
-- */
--
--#define NIL 0
--/* Tail of hash chains */
--
--#ifndef TOO_FAR
--#  define TOO_FAR 4096
--#endif
--/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
--
--/* Values for max_lazy_match, good_match and max_chain_length, depending on
-- * the desired pack level (0..9). The values given below have been tuned to
-- * exclude worst case performance for pathological files. Better values may be
-- * found for specific files.
-- */
--typedef struct config_s {
--   ush good_length; /* reduce lazy search above this match length */
--   ush max_lazy;    /* do not perform lazy search above this match length */
--   ush nice_length; /* quit search above this match length */
--   ush max_chain;
--   compress_func func;
--} config;
--
--#ifdef FASTEST
--local const config configuration_table[2] = {
--/*      good lazy nice chain */
--/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
--/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
--#else
--local const config configuration_table[10] = {
--/*      good lazy nice chain */
--/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
--/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
--/* 2 */ {4,    5, 16,    8, deflate_fast},
--/* 3 */ {4,    6, 32,   32, deflate_fast},
--
--/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
--/* 5 */ {8,   16, 32,   32, deflate_slow},
--/* 6 */ {8,   16, 128, 128, deflate_slow},
--/* 7 */ {8,   32, 128, 256, deflate_slow},
--/* 8 */ {32, 128, 258, 1024, deflate_slow},
--/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
--#endif
--
--/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
-- * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
-- * meaning.
-- */
--
--/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
--#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
--
--/* ===========================================================================
-- * Update a hash value with the given input byte
-- * IN  assertion: all calls to UPDATE_HASH are made with consecutive input
-- *    characters, so that a running hash key can be computed from the previous
-- *    key instead of complete recalculation each time.
-- */
--#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
--
--
--/* ===========================================================================
-- * Insert string str in the dictionary and set match_head to the previous head
-- * of the hash chain (the most recent string with same hash key). Return
-- * the previous length of the hash chain.
-- * If this file is compiled with -DFASTEST, the compression level is forced
-- * to 1, and no hash chains are maintained.
-- * IN  assertion: all calls to INSERT_STRING are made with consecutive input
-- *    characters and the first MIN_MATCH bytes of str are valid (except for
-- *    the last MIN_MATCH-1 bytes of the input file).
-- */
--#ifdef FASTEST
--#define INSERT_STRING(s, str, match_head) \
--   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
--    match_head = s->head[s->ins_h], \
--    s->head[s->ins_h] = (Pos)(str))
--#else
--#define INSERT_STRING(s, str, match_head) \
--   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
--    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
--    s->head[s->ins_h] = (Pos)(str))
--#endif
--
--/* ===========================================================================
-- * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
-- * prev[] will be initialized on the fly.
-- */
--#define CLEAR_HASH(s) \
--    s->head[s->hash_size-1] = NIL; \
--    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
--
--/* ===========================================================================
-- * Slide the hash table when sliding the window down (could be avoided with 32
-- * bit values at the expense of memory usage). We slide even when level == 0 to
-- * keep the hash table consistent if we switch back to level > 0 later.
-- */
--local void slide_hash(s)
--    deflate_state *s;
--{
--    unsigned n, m;
--    Posf *p;
--    uInt wsize = s->w_size;
--
--    n = s->hash_size;
--    p = &s->head[n];
--    do {
--        m = *--p;
--        *p = (Pos)(m >= wsize ? m - wsize : NIL);
--    } while (--n);
--    n = wsize;
--#ifndef FASTEST
--    p = &s->prev[n];
--    do {
--        m = *--p;
--        *p = (Pos)(m >= wsize ? m - wsize : NIL);
--        /* If n is not on any hash chain, prev[n] is garbage but
--         * its value will never be used.
--         */
--    } while (--n);
--#endif
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateInit_(strm, level, version, stream_size)
--    z_streamp strm;
--    int level;
--    const char *version;
--    int stream_size;
--{
--    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
--                         Z_DEFAULT_STRATEGY, version, stream_size);
--    /* To do: ignore strm->next_in if we use it as window */
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
--                  version, stream_size)
--    z_streamp strm;
--    int  level;
--    int  method;
--    int  windowBits;
--    int  memLevel;
--    int  strategy;
--    const char *version;
--    int stream_size;
--{
--    deflate_state *s;
--    int wrap = 1;
--    static const char my_version[] = ZLIB_VERSION;
--
--    ushf *overlay;
--    /* We overlay pending_buf and d_buf+l_buf. This works since the average
--     * output size for (length,distance) codes is <= 24 bits.
--     */
--
--    if (version == Z_NULL || version[0] != my_version[0] ||
--        stream_size != sizeof(z_stream)) {
--        return Z_VERSION_ERROR;
--    }
--    if (strm == Z_NULL) return Z_STREAM_ERROR;
--
--    strm->msg = Z_NULL;
--    if (strm->zalloc == (alloc_func)0) {
--#ifdef Z_SOLO
--        return Z_STREAM_ERROR;
--#else
--        strm->zalloc = zcalloc;
--        strm->opaque = (voidpf)0;
--#endif
--    }
--    if (strm->zfree == (free_func)0)
--#ifdef Z_SOLO
--        return Z_STREAM_ERROR;
--#else
--        strm->zfree = zcfree;
--#endif
--
--#ifdef FASTEST
--    if (level != 0) level = 1;
--#else
--    if (level == Z_DEFAULT_COMPRESSION) level = 6;
--#endif
--
--    if (windowBits < 0) { /* suppress zlib wrapper */
--        wrap = 0;
--        windowBits = -windowBits;
--    }
--#ifdef GZIP
--    else if (windowBits > 15) {
--        wrap = 2;       /* write gzip wrapper instead */
--        windowBits -= 16;
--    }
--#endif
--    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
--        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
--        strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
--        return Z_STREAM_ERROR;
--    }
--    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
--    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
--    if (s == Z_NULL) return Z_MEM_ERROR;
--    strm->state = (struct internal_state FAR *)s;
--    s->strm = strm;
--    s->status = INIT_STATE;     /* to pass state test in deflateReset() */
--
--    s->wrap = wrap;
--    s->gzhead = Z_NULL;
--    s->w_bits = (uInt)windowBits;
--    s->w_size = 1 << s->w_bits;
--    s->w_mask = s->w_size - 1;
--
--    s->hash_bits = (uInt)memLevel + 7;
--    s->hash_size = 1 << s->hash_bits;
--    s->hash_mask = s->hash_size - 1;
--    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
--
--    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
--    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
--    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
--
--    s->high_water = 0;      /* nothing written to s->window yet */
--
--    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
--
--    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
--    s->pending_buf = (uchf *) overlay;
--    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
--
--    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
--        s->pending_buf == Z_NULL) {
--        s->status = FINISH_STATE;
--        strm->msg = ERR_MSG(Z_MEM_ERROR);
--        deflateEnd (strm);
--        return Z_MEM_ERROR;
--    }
--    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
--    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
--
--    s->level = level;
--    s->strategy = strategy;
--    s->method = (Byte)method;
--
--    return deflateReset(strm);
--}
--
--/* =========================================================================
-- * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
-- */
--local int deflateStateCheck (strm)
--    z_streamp strm;
--{
--    deflate_state *s;
--    if (strm == Z_NULL ||
--        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
--        return 1;
--    s = strm->state;
--    if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
--#ifdef GZIP
--                                           s->status != GZIP_STATE &&
--#endif
--                                           s->status != EXTRA_STATE &&
--                                           s->status != NAME_STATE &&
--                                           s->status != COMMENT_STATE &&
--                                           s->status != HCRC_STATE &&
--                                           s->status != BUSY_STATE &&
--                                           s->status != FINISH_STATE))
--        return 1;
--    return 0;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
--    z_streamp strm;
--    const Bytef *dictionary;
--    uInt  dictLength;
--{
--    deflate_state *s;
--    uInt str, n;
--    int wrap;
--    unsigned avail;
--    z_const unsigned char *next;
--
--    if (deflateStateCheck(strm) || dictionary == Z_NULL)
--        return Z_STREAM_ERROR;
--    s = strm->state;
--    wrap = s->wrap;
--    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
--        return Z_STREAM_ERROR;
--
--    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
--    if (wrap == 1)
--        strm->adler = adler32(strm->adler, dictionary, dictLength);
--    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
--
--    /* if dictionary would fill window, just replace the history */
--    if (dictLength >= s->w_size) {
--        if (wrap == 0) {            /* already empty otherwise */
--            CLEAR_HASH(s);
--            s->strstart = 0;
--            s->block_start = 0L;
--            s->insert = 0;
--        }
--        dictionary += dictLength - s->w_size;  /* use the tail */
--        dictLength = s->w_size;
--    }
--
--    /* insert dictionary into window and hash */
--    avail = strm->avail_in;
--    next = strm->next_in;
--    strm->avail_in = dictLength;
--    strm->next_in = (z_const Bytef *)dictionary;
--    fill_window(s);
--    while (s->lookahead >= MIN_MATCH) {
--        str = s->strstart;
--        n = s->lookahead - (MIN_MATCH-1);
--        do {
--            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
--#ifndef FASTEST
--            s->prev[str & s->w_mask] = s->head[s->ins_h];
--#endif
--            s->head[s->ins_h] = (Pos)str;
--            str++;
--        } while (--n);
--        s->strstart = str;
--        s->lookahead = MIN_MATCH-1;
--        fill_window(s);
--    }
--    s->strstart += s->lookahead;
--    s->block_start = (long)s->strstart;
--    s->insert = s->lookahead;
--    s->lookahead = 0;
--    s->match_length = s->prev_length = MIN_MATCH-1;
--    s->match_available = 0;
--    strm->next_in = next;
--    strm->avail_in = avail;
--    s->wrap = wrap;
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)
--    z_streamp strm;
--    Bytef *dictionary;
--    uInt  *dictLength;
--{
--    deflate_state *s;
--    uInt len;
--
--    if (deflateStateCheck(strm))
--        return Z_STREAM_ERROR;
--    s = strm->state;
--    len = s->strstart + s->lookahead;
--    if (len > s->w_size)
--        len = s->w_size;
--    if (dictionary != Z_NULL && len)
--        zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
--    if (dictLength != Z_NULL)
--        *dictLength = len;
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateResetKeep (strm)
--    z_streamp strm;
--{
--    deflate_state *s;
--
--    if (deflateStateCheck(strm)) {
--        return Z_STREAM_ERROR;
--    }
--
--    strm->total_in = strm->total_out = 0;
--    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
--    strm->data_type = Z_UNKNOWN;
--
--    s = (deflate_state *)strm->state;
--    s->pending = 0;
--    s->pending_out = s->pending_buf;
--
--    if (s->wrap < 0) {
--        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
--    }
--    s->status =
--#ifdef GZIP
--        s->wrap == 2 ? GZIP_STATE :
--#endif
--        s->wrap ? INIT_STATE : BUSY_STATE;
--    strm->adler =
--#ifdef GZIP
--        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
--#endif
--        adler32(0L, Z_NULL, 0);
--    s->last_flush = Z_NO_FLUSH;
--
--    _tr_init(s);
--
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateReset (strm)
--    z_streamp strm;
--{
--    int ret;
--
--    ret = deflateResetKeep(strm);
--    if (ret == Z_OK)
--        lm_init(strm->state);
--    return ret;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateSetHeader (strm, head)
--    z_streamp strm;
--    gz_headerp head;
--{
--    if (deflateStateCheck(strm) || strm->state->wrap != 2)
--        return Z_STREAM_ERROR;
--    strm->state->gzhead = head;
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflatePending (strm, pending, bits)
--    unsigned *pending;
--    int *bits;
--    z_streamp strm;
--{
--    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
--    if (pending != Z_NULL)
--        *pending = strm->state->pending;
--    if (bits != Z_NULL)
--        *bits = strm->state->bi_valid;
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflatePrime (strm, bits, value)
--    z_streamp strm;
--    int bits;
--    int value;
--{
--    deflate_state *s;
--    int put;
--
--    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
--    s = strm->state;
--    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
--        return Z_BUF_ERROR;
--    do {
--        put = Buf_size - s->bi_valid;
--        if (put > bits)
--            put = bits;
--        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
--        s->bi_valid += put;
--        _tr_flush_bits(s);
--        value >>= put;
--        bits -= put;
--    } while (bits);
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateParams(strm, level, strategy)
--    z_streamp strm;
--    int level;
--    int strategy;
--{
--    deflate_state *s;
--    compress_func func;
--
--    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
--    s = strm->state;
--
--#ifdef FASTEST
--    if (level != 0) level = 1;
--#else
--    if (level == Z_DEFAULT_COMPRESSION) level = 6;
--#endif
--    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
--        return Z_STREAM_ERROR;
--    }
--    func = configuration_table[s->level].func;
--
--    if ((strategy != s->strategy || func != configuration_table[level].func) &&
--        s->high_water) {
--        /* Flush the last buffer: */
--        int err = deflate(strm, Z_BLOCK);
--        if (err == Z_STREAM_ERROR)
--            return err;
--        if (strm->avail_out == 0)
--            return Z_BUF_ERROR;
--    }
--    if (s->level != level) {
--        if (s->level == 0 && s->matches != 0) {
--            if (s->matches == 1)
--                slide_hash(s);
--            else
--                CLEAR_HASH(s);
--            s->matches = 0;
--        }
--        s->level = level;
--        s->max_lazy_match   = configuration_table[level].max_lazy;
--        s->good_match       = configuration_table[level].good_length;
--        s->nice_match       = configuration_table[level].nice_length;
--        s->max_chain_length = configuration_table[level].max_chain;
--    }
--    s->strategy = strategy;
--    return Z_OK;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
--    z_streamp strm;
--    int good_length;
--    int max_lazy;
--    int nice_length;
--    int max_chain;
--{
--    deflate_state *s;
--
--    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
--    s = strm->state;
--    s->good_match = (uInt)good_length;
--    s->max_lazy_match = (uInt)max_lazy;
--    s->nice_match = nice_length;
--    s->max_chain_length = (uInt)max_chain;
--    return Z_OK;
--}
--
--/* =========================================================================
-- * For the default windowBits of 15 and memLevel of 8, this function returns
-- * a close to exact, as well as small, upper bound on the compressed size.
-- * They are coded as constants here for a reason--if the #define's are
-- * changed, then this function needs to be changed as well.  The return
-- * value for 15 and 8 only works for those exact settings.
-- *
-- * For any setting other than those defaults for windowBits and memLevel,
-- * the value returned is a conservative worst case for the maximum expansion
-- * resulting from using fixed blocks instead of stored blocks, which deflate
-- * can emit on compressed data for some combinations of the parameters.
-- *
-- * This function could be more sophisticated to provide closer upper bounds for
-- * every combination of windowBits and memLevel.  But even the conservative
-- * upper bound of about 14% expansion does not seem onerous for output buffer
-- * allocation.
-- */
--uLong ZEXPORT deflateBound(strm, sourceLen)
--    z_streamp strm;
--    uLong sourceLen;
--{
--    deflate_state *s;
--    uLong complen, wraplen;
--
--    /* conservative upper bound for compressed data */
--    complen = sourceLen +
--              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
--
--    /* if can't get parameters, return conservative bound plus zlib wrapper */
--    if (deflateStateCheck(strm))
--        return complen + 6;
--
--    /* compute wrapper length */
--    s = strm->state;
--    switch (s->wrap) {
--    case 0:                                 /* raw deflate */
--        wraplen = 0;
--        break;
--    case 1:                                 /* zlib wrapper */
--        wraplen = 6 + (s->strstart ? 4 : 0);
--        break;
--#ifdef GZIP
--    case 2:                                 /* gzip wrapper */
--        wraplen = 18;
--        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
--            Bytef *str;
--            if (s->gzhead->extra != Z_NULL)
--                wraplen += 2 + s->gzhead->extra_len;
--            str = s->gzhead->name;
--            if (str != Z_NULL)
--                do {
--                    wraplen++;
--                } while (*str++);
--            str = s->gzhead->comment;
--            if (str != Z_NULL)
--                do {
--                    wraplen++;
--                } while (*str++);
--            if (s->gzhead->hcrc)
--                wraplen += 2;
--        }
--        break;
--#endif
--    default:                                /* for compiler happiness */
--        wraplen = 6;
--    }
--
--    /* if not default parameters, return conservative bound */
--    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
--        return complen + wraplen;
--
--    /* default settings: return tight bound for that case */
--    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
--           (sourceLen >> 25) + 13 - 6 + wraplen;
--}
--
--/* =========================================================================
-- * Put a short in the pending buffer. The 16-bit value is put in MSB order.
-- * IN assertion: the stream state is correct and there is enough room in
-- * pending_buf.
-- */
--local void putShortMSB (s, b)
--    deflate_state *s;
--    uInt b;
--{
--    put_byte(s, (Byte)(b >> 8));
--    put_byte(s, (Byte)(b & 0xff));
--}
--
--/* =========================================================================
-- * Flush as much pending output as possible. All deflate() output, except for
-- * some deflate_stored() output, goes through this function so some
-- * applications may wish to modify it to avoid allocating a large
-- * strm->next_out buffer and copying into it. (See also read_buf()).
-- */
--local void flush_pending(strm)
--    z_streamp strm;
--{
--    unsigned len;
--    deflate_state *s = strm->state;
--
--    _tr_flush_bits(s);
--    len = s->pending;
--    if (len > strm->avail_out) len = strm->avail_out;
--    if (len == 0) return;
--
--    zmemcpy(strm->next_out, s->pending_out, len);
--    strm->next_out  += len;
--    s->pending_out  += len;
--    strm->total_out += len;
--    strm->avail_out -= len;
--    s->pending      -= len;
--    if (s->pending == 0) {
--        s->pending_out = s->pending_buf;
--    }
--}
--
--/* ===========================================================================
-- * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
-- */
--#define HCRC_UPDATE(beg) \
--    do { \
--        if (s->gzhead->hcrc && s->pending > (beg)) \
--            strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
--                                s->pending - (beg)); \
--    } while (0)
--
--/* ========================================================================= */
--int ZEXPORT deflate (strm, flush)
--    z_streamp strm;
--    int flush;
--{
--    int old_flush; /* value of flush param for previous deflate call */
--    deflate_state *s;
--
--    if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
--        return Z_STREAM_ERROR;
--    }
--    s = strm->state;
--
--    if (strm->next_out == Z_NULL ||
--        (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
--        (s->status == FINISH_STATE && flush != Z_FINISH)) {
--        ERR_RETURN(strm, Z_STREAM_ERROR);
--    }
--    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
--
--    old_flush = s->last_flush;
--    s->last_flush = flush;
--
--    /* Flush as much pending output as possible */
--    if (s->pending != 0) {
--        flush_pending(strm);
--        if (strm->avail_out == 0) {
--            /* Since avail_out is 0, deflate will be called again with
--             * more output space, but possibly with both pending and
--             * avail_in equal to zero. There won't be anything to do,
--             * but this is not an error situation so make sure we
--             * return OK instead of BUF_ERROR at next call of deflate:
--             */
--            s->last_flush = -1;
--            return Z_OK;
--        }
--
--    /* Make sure there is something to do and avoid duplicate consecutive
--     * flushes. For repeated and useless calls with Z_FINISH, we keep
--     * returning Z_STREAM_END instead of Z_BUF_ERROR.
--     */
--    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
--               flush != Z_FINISH) {
--        ERR_RETURN(strm, Z_BUF_ERROR);
--    }
--
--    /* User must not provide more input after the first FINISH: */
--    if (s->status == FINISH_STATE && strm->avail_in != 0) {
--        ERR_RETURN(strm, Z_BUF_ERROR);
--    }
--
--    /* Write the header */
--    if (s->status == INIT_STATE) {
--        /* zlib header */
--        uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
--        uInt level_flags;
--
--        if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
--            level_flags = 0;
--        else if (s->level < 6)
--            level_flags = 1;
--        else if (s->level == 6)
--            level_flags = 2;
--        else
--            level_flags = 3;
--        header |= (level_flags << 6);
--        if (s->strstart != 0) header |= PRESET_DICT;
--        header += 31 - (header % 31);
--
--        putShortMSB(s, header);
--
--        /* Save the adler32 of the preset dictionary: */
--        if (s->strstart != 0) {
--            putShortMSB(s, (uInt)(strm->adler >> 16));
--            putShortMSB(s, (uInt)(strm->adler & 0xffff));
--        }
--        strm->adler = adler32(0L, Z_NULL, 0);
--        s->status = BUSY_STATE;
--
--        /* Compression must start with an empty pending buffer */
--        flush_pending(strm);
--        if (s->pending != 0) {
--            s->last_flush = -1;
--            return Z_OK;
--        }
--    }
--#ifdef GZIP
--    if (s->status == GZIP_STATE) {
--        /* gzip header */
--        strm->adler = crc32(0L, Z_NULL, 0);
--        put_byte(s, 31);
--        put_byte(s, 139);
--        put_byte(s, 8);
--        if (s->gzhead == Z_NULL) {
--            put_byte(s, 0);
--            put_byte(s, 0);
--            put_byte(s, 0);
--            put_byte(s, 0);
--            put_byte(s, 0);
--            put_byte(s, s->level == 9 ? 2 :
--                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
--                      4 : 0));
--            put_byte(s, OS_CODE);
--            s->status = BUSY_STATE;
--
--            /* Compression must start with an empty pending buffer */
--            flush_pending(strm);
--            if (s->pending != 0) {
--                s->last_flush = -1;
--                return Z_OK;
--            }
--        }
--        else {
--            put_byte(s, (s->gzhead->text ? 1 : 0) +
--                     (s->gzhead->hcrc ? 2 : 0) +
--                     (s->gzhead->extra == Z_NULL ? 0 : 4) +
--                     (s->gzhead->name == Z_NULL ? 0 : 8) +
--                     (s->gzhead->comment == Z_NULL ? 0 : 16)
--                     );
--            put_byte(s, (Byte)(s->gzhead->time & 0xff));
--            put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
--            put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
--            put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
--            put_byte(s, s->level == 9 ? 2 :
--                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
--                      4 : 0));
--            put_byte(s, s->gzhead->os & 0xff);
--            if (s->gzhead->extra != Z_NULL) {
--                put_byte(s, s->gzhead->extra_len & 0xff);
--                put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
--            }
--            if (s->gzhead->hcrc)
--                strm->adler = crc32(strm->adler, s->pending_buf,
--                                    s->pending);
--            s->gzindex = 0;
--            s->status = EXTRA_STATE;
--        }
--    }
--    if (s->status == EXTRA_STATE) {
--        if (s->gzhead->extra != Z_NULL) {
--            ulg beg = s->pending;   /* start of bytes to update crc */
--            uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
--            while (s->pending + left > s->pending_buf_size) {
--                uInt copy = s->pending_buf_size - s->pending;
--                zmemcpy(s->pending_buf + s->pending,
--                        s->gzhead->extra + s->gzindex, copy);
--                s->pending = s->pending_buf_size;
--                HCRC_UPDATE(beg);
--                s->gzindex += copy;
--                flush_pending(strm);
--                if (s->pending != 0) {
--                    s->last_flush = -1;
--                    return Z_OK;
--                }
--                beg = 0;
--                left -= copy;
--            }
--            zmemcpy(s->pending_buf + s->pending,
--                    s->gzhead->extra + s->gzindex, left);
--            s->pending += left;
--            HCRC_UPDATE(beg);
--            s->gzindex = 0;
--        }
--        s->status = NAME_STATE;
--    }
--    if (s->status == NAME_STATE) {
--        if (s->gzhead->name != Z_NULL) {
--            ulg beg = s->pending;   /* start of bytes to update crc */
--            int val;
--            do {
--                if (s->pending == s->pending_buf_size) {
--                    HCRC_UPDATE(beg);
--                    flush_pending(strm);
--                    if (s->pending != 0) {
--                        s->last_flush = -1;
--                        return Z_OK;
--                    }
--                    beg = 0;
--                }
--                val = s->gzhead->name[s->gzindex++];
--                put_byte(s, val);
--            } while (val != 0);
--            HCRC_UPDATE(beg);
--            s->gzindex = 0;
--        }
--        s->status = COMMENT_STATE;
--    }
--    if (s->status == COMMENT_STATE) {
--        if (s->gzhead->comment != Z_NULL) {
--            ulg beg = s->pending;   /* start of bytes to update crc */
--            int val;
--            do {
--                if (s->pending == s->pending_buf_size) {
--                    HCRC_UPDATE(beg);
--                    flush_pending(strm);
--                    if (s->pending != 0) {
--                        s->last_flush = -1;
--                        return Z_OK;
--                    }
--                    beg = 0;
--                }
--                val = s->gzhead->comment[s->gzindex++];
--                put_byte(s, val);
--            } while (val != 0);
--            HCRC_UPDATE(beg);
--        }
--        s->status = HCRC_STATE;
--    }
--    if (s->status == HCRC_STATE) {
--        if (s->gzhead->hcrc) {
--            if (s->pending + 2 > s->pending_buf_size) {
--                flush_pending(strm);
--                if (s->pending != 0) {
--                    s->last_flush = -1;
--                    return Z_OK;
--                }
--            }
--            put_byte(s, (Byte)(strm->adler & 0xff));
--            put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
--            strm->adler = crc32(0L, Z_NULL, 0);
--        }
--        s->status = BUSY_STATE;
--
--        /* Compression must start with an empty pending buffer */
--        flush_pending(strm);
--        if (s->pending != 0) {
--            s->last_flush = -1;
--            return Z_OK;
--        }
--    }
--#endif
--
--    /* Start a new block or continue the current one.
--     */
--    if (strm->avail_in != 0 || s->lookahead != 0 ||
--        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
--        block_state bstate;
--
--        bstate = s->level == 0 ? deflate_stored(s, flush) :
--                 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
--                 s->strategy == Z_RLE ? deflate_rle(s, flush) :
--                 (*(configuration_table[s->level].func))(s, flush);
--
--        if (bstate == finish_started || bstate == finish_done) {
--            s->status = FINISH_STATE;
--        }
--        if (bstate == need_more || bstate == finish_started) {
--            if (strm->avail_out == 0) {
--                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
--            }
--            return Z_OK;
--            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
--             * of deflate should use the same flush parameter to make sure
--             * that the flush is complete. So we don't have to output an
--             * empty block here, this will be done at next call. This also
--             * ensures that for a very small output buffer, we emit at most
--             * one empty block.
--             */
--        }
--        if (bstate == block_done) {
--            if (flush == Z_PARTIAL_FLUSH) {
--                _tr_align(s);
--            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
--                _tr_stored_block(s, (char*)0, 0L, 0);
--                /* For a full flush, this empty block will be recognized
--                 * as a special marker by inflate_sync().
--                 */
--                if (flush == Z_FULL_FLUSH) {
--                    CLEAR_HASH(s);             /* forget history */
--                    if (s->lookahead == 0) {
--                        s->strstart = 0;
--                        s->block_start = 0L;
--                        s->insert = 0;
--                    }
--                }
--            }
--            flush_pending(strm);
--            if (strm->avail_out == 0) {
--              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
--              return Z_OK;
--            }
--        }
--    }
--
--    if (flush != Z_FINISH) return Z_OK;
--    if (s->wrap <= 0) return Z_STREAM_END;
--
--    /* Write the trailer */
--#ifdef GZIP
--    if (s->wrap == 2) {
--        put_byte(s, (Byte)(strm->adler & 0xff));
--        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
--        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
--        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
--        put_byte(s, (Byte)(strm->total_in & 0xff));
--        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
--        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
--        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
--    }
--    else
--#endif
--    {
--        putShortMSB(s, (uInt)(strm->adler >> 16));
--        putShortMSB(s, (uInt)(strm->adler & 0xffff));
--    }
--    flush_pending(strm);
--    /* If avail_out is zero, the application will call deflate again
--     * to flush the rest.
--     */
--    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
--    return s->pending != 0 ? Z_OK : Z_STREAM_END;
--}
--
--/* ========================================================================= */
--int ZEXPORT deflateEnd (strm)
--    z_streamp strm;
--{
--    int status;
--
--    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
--
--    status = strm->state->status;
--
--    /* Deallocate in reverse order of allocations: */
--    TRY_FREE(strm, strm->state->pending_buf);
--    TRY_FREE(strm, strm->state->head);
--    TRY_FREE(strm, strm->state->prev);
--    TRY_FREE(strm, strm->state->window);
--
--    ZFREE(strm, strm->state);
--    strm->state = Z_NULL;
--
--    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
--}
--
--/* =========================================================================
-- * Copy the source state to the destination state.
-- * To simplify the source, this is not supported for 16-bit MSDOS (which
-- * doesn't have enough memory anyway to duplicate compression states).
-- */
--int ZEXPORT deflateCopy (dest, source)
--    z_streamp dest;
--    z_streamp source;
--{
--#ifdef MAXSEG_64K
--    return Z_STREAM_ERROR;
--#else
--    deflate_state *ds;
--    deflate_state *ss;
--    ushf *overlay;
--
--
--    if (deflateStateCheck(source) || dest == Z_NULL) {
--        return Z_STREAM_ERROR;
--    }
--
--    ss = source->state;
--
--    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
--
--    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
--    if (ds == Z_NULL) return Z_MEM_ERROR;
--    dest->state = (struct internal_state FAR *) ds;
--    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
--    ds->strm = dest;
--
--    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
--    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
--    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
--    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
--    ds->pending_buf = (uchf *) overlay;
--
--    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
--        ds->pending_buf == Z_NULL) {
--        deflateEnd (dest);
--        return Z_MEM_ERROR;
--    }
--    /* following zmemcpy do not work for 16-bit MSDOS */
--    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
--    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
--    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
--    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
--
--    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
--    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
--    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
--
--    ds->l_desc.dyn_tree = ds->dyn_ltree;
--    ds->d_desc.dyn_tree = ds->dyn_dtree;
--    ds->bl_desc.dyn_tree = ds->bl_tree;
--
--    return Z_OK;
--#endif /* MAXSEG_64K */
--}
--
--/* ===========================================================================
-- * Read a new buffer from the current input stream, update the adler32
-- * and total number of bytes read.  All deflate() input goes through
-- * this function so some applications may wish to modify it to avoid
-- * allocating a large strm->next_in buffer and copying from it.
-- * (See also flush_pending()).
-- */
--local unsigned read_buf(strm, buf, size)
--    z_streamp strm;
--    Bytef *buf;
--    unsigned size;
--{
--    unsigned len = strm->avail_in;
--
--    if (len > size) len = size;
--    if (len == 0) return 0;
--
--    strm->avail_in  -= len;
--
--    zmemcpy(buf, strm->next_in, len);
--    if (strm->state->wrap == 1) {
--        strm->adler = adler32(strm->adler, buf, len);
--    }
--#ifdef GZIP
--    else if (strm->state->wrap == 2) {
--        strm->adler = crc32(strm->adler, buf, len);
--    }
--#endif
--    strm->next_in  += len;
--    strm->total_in += len;
--
--    return len;
--}
--
--/* ===========================================================================
-- * Initialize the "longest match" routines for a new zlib stream
-- */
--local void lm_init (s)
--    deflate_state *s;
--{
--    s->window_size = (ulg)2L*s->w_size;
--
--    CLEAR_HASH(s);
--
--    /* Set the default configuration parameters:
--     */
--    s->max_lazy_match   = configuration_table[s->level].max_lazy;
--    s->good_match       = configuration_table[s->level].good_length;
--    s->nice_match       = configuration_table[s->level].nice_length;
--    s->max_chain_length = configuration_table[s->level].max_chain;
--
--    s->strstart = 0;
--    s->block_start = 0L;
--    s->lookahead = 0;
--    s->insert = 0;
--    s->match_length = s->prev_length = MIN_MATCH-1;
--    s->match_available = 0;
--    s->ins_h = 0;
--#ifndef FASTEST
--#ifdef ASMV
--    match_init(); /* initialize the asm code */
--#endif
--#endif
--}
--
--#ifndef FASTEST
--/* ===========================================================================
-- * Set match_start to the longest match starting at the given string and
-- * return its length. Matches shorter or equal to prev_length are discarded,
-- * in which case the result is equal to prev_length and match_start is
-- * garbage.
-- * IN assertions: cur_match is the head of the hash chain for the current
-- *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
-- * OUT assertion: the match length is not greater than s->lookahead.
-- */
--#ifndef ASMV
--/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
-- * match.S. The code will be functionally equivalent.
-- */
--local uInt longest_match(s, cur_match)
--    deflate_state *s;
--    IPos cur_match;                             /* current match */
--{
--    unsigned chain_length = s->max_chain_length;/* max hash chain length */
--    register Bytef *scan = s->window + s->strstart; /* current string */
--    register Bytef *match;                      /* matched string */
--    register int len;                           /* length of current match */
--    int best_len = (int)s->prev_length;         /* best match length so far */
--    int nice_match = s->nice_match;             /* stop if match long enough */
--    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
--        s->strstart - (IPos)MAX_DIST(s) : NIL;
--    /* Stop when cur_match becomes <= limit. To simplify the code,
--     * we prevent matches with the string of window index 0.
--     */
--    Posf *prev = s->prev;
--    uInt wmask = s->w_mask;
--
--#ifdef UNALIGNED_OK
--    /* Compare two bytes at a time. Note: this is not always beneficial.
--     * Try with and without -DUNALIGNED_OK to check.
--     */
--    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
--    register ush scan_start = *(ushf*)scan;
--    register ush scan_end   = *(ushf*)(scan+best_len-1);
--#else
--    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
--    register Byte scan_end1  = scan[best_len-1];
--    register Byte scan_end   = scan[best_len];
--#endif
--
--    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
--     * It is easy to get rid of this optimization if necessary.
--     */
--    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
--
--    /* Do not waste too much time if we already have a good match: */
--    if (s->prev_length >= s->good_match) {
--        chain_length >>= 2;
--    }
--    /* Do not look for matches beyond the end of the input. This is necessary
--     * to make deflate deterministic.
--     */
--    if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
--
--    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
--
--    do {
--        Assert(cur_match < s->strstart, "no future");
--        match = s->window + cur_match;
--
--        /* Skip to next match if the match length cannot increase
--         * or if the match length is less than 2.  Note that the checks below
--         * for insufficient lookahead only occur occasionally for performance
--         * reasons.  Therefore uninitialized memory will be accessed, and
--         * conditional jumps will be made that depend on those values.
--         * However the length of the match is limited to the lookahead, so
--         * the output of deflate is not affected by the uninitialized values.
--         */
--#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
--        /* This code assumes sizeof(unsigned short) == 2. Do not use
--         * UNALIGNED_OK if your compiler uses a different size.
--         */
--        if (*(ushf*)(match+best_len-1) != scan_end ||
--            *(ushf*)match != scan_start) continue;
--
--        /* It is not necessary to compare scan[2] and match[2] since they are
--         * always equal when the other bytes match, given that the hash keys
--         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
--         * strstart+3, +5, ... up to strstart+257. We check for insufficient
--         * lookahead only every 4th comparison; the 128th check will be made
--         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
--         * necessary to put more guard bytes at the end of the window, or
--         * to check more often for insufficient lookahead.
--         */
--        Assert(scan[2] == match[2], "scan[2]?");
--        scan++, match++;
--        do {
--        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
--                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
--                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
--                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
--                 scan < strend);
--        /* The funny "do {}" generates better code on most compilers */
--
--        /* Here, scan <= window+strstart+257 */
--        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
--        if (*scan == *match) scan++;
--
--        len = (MAX_MATCH - 1) - (int)(strend-scan);
--        scan = strend - (MAX_MATCH-1);
--
--#else /* UNALIGNED_OK */
--
--        if (match[best_len]   != scan_end  ||
--            match[best_len-1] != scan_end1 ||
--            *match            != *scan     ||
--            *++match          != scan[1])      continue;
--
--        /* The check at best_len-1 can be removed because it will be made
--         * again later. (This heuristic is not always a win.)
--         * It is not necessary to compare scan[2] and match[2] since they
--         * are always equal when the other bytes match, given that
--         * the hash keys are equal and that HASH_BITS >= 8.
--         */
--        scan += 2, match++;
--        Assert(*scan == *match, "match[2]?");
--
--        /* We check for insufficient lookahead only every 8th comparison;
--         * the 256th check will be made at strstart+258.
--         */
--        do {
--        } while (*++scan == *++match && *++scan == *++match &&
--                 *++scan == *++match && *++scan == *++match &&
--                 *++scan == *++match && *++scan == *++match &&
--                 *++scan == *++match && *++scan == *++match &&
--                 scan < strend);
--
--        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
--
--        len = MAX_MATCH - (int)(strend - scan);
--        scan = strend - MAX_MATCH;
--
--#endif /* UNALIGNED_OK */
--
--        if (len > best_len) {
--            s->match_start = cur_match;
--            best_len = len;
--            if (len >= nice_match) break;
--#ifdef UNALIGNED_OK
--            scan_end = *(ushf*)(scan+best_len-1);
--#else
--            scan_end1  = scan[best_len-1];
--            scan_end   = scan[best_len];
--#endif
--        }
--    } while ((cur_match = prev[cur_match & wmask]) > limit
--             && --chain_length != 0);
--
--    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
--    return s->lookahead;
--}
--#endif /* ASMV */
--
--#else /* FASTEST */
--
--/* ---------------------------------------------------------------------------
-- * Optimized version for FASTEST only
-- */
--local uInt longest_match(s, cur_match)
--    deflate_state *s;
--    IPos cur_match;                             /* current match */
--{
--    register Bytef *scan = s->window + s->strstart; /* current string */
--    register Bytef *match;                       /* matched string */
--    register int len;                           /* length of current match */
--    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
--
--    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
--     * It is easy to get rid of this optimization if necessary.
--     */
--    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
--
--    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
--
--    Assert(cur_match < s->strstart, "no future");
--
--    match = s->window + cur_match;
--
--    /* Return failure if the match length is less than 2:
--     */
--    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
--
--    /* The check at best_len-1 can be removed because it will be made
--     * again later. (This heuristic is not always a win.)
--     * It is not necessary to compare scan[2] and match[2] since they
--     * are always equal when the other bytes match, given that
--     * the hash keys are equal and that HASH_BITS >= 8.
--     */
--    scan += 2, match += 2;
--    Assert(*scan == *match, "match[2]?");
--
--    /* We check for insufficient lookahead only every 8th comparison;
--     * the 256th check will be made at strstart+258.
--     */
--    do {
--    } while (*++scan == *++match && *++scan == *++match &&
--             *++scan == *++match && *++scan == *++match &&
--             *++scan == *++match && *++scan == *++match &&
--             *++scan == *++match && *++scan == *++match &&
--             scan < strend);
--
--    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
--
--    len = MAX_MATCH - (int)(strend - scan);
--
--    if (len < MIN_MATCH) return MIN_MATCH - 1;
--
--    s->match_start = cur_match;
--    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
--}
--
--#endif /* FASTEST */
--
--#ifdef ZLIB_DEBUG
--
--#define EQUAL 0
--/* result of memcmp for equal strings */
--
--/* ===========================================================================
-- * Check that the match at match_start is indeed a match.
-- */
--local void check_match(s, start, match, length)
--    deflate_state *s;
--    IPos start, match;
--    int length;
--{
--    /* check that the match is indeed a match */
--    if (zmemcmp(s->window + match,
--                s->window + start, length) != EQUAL) {
--        fprintf(stderr, " start %u, match %u, length %d\n",
--                start, match, length);
--        do {
--            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
--        } while (--length != 0);
--        z_error("invalid match");
--    }
--    if (z_verbose > 1) {
--        fprintf(stderr,"\\[%d,%d]", start-match, length);
--        do { putc(s->window[start++], stderr); } while (--length != 0);
--    }
--}
--#else
--#  define check_match(s, start, match, length)
--#endif /* ZLIB_DEBUG */
--
--/* ===========================================================================
-- * Fill the window when the lookahead becomes insufficient.
-- * Updates strstart and lookahead.
-- *
-- * IN assertion: lookahead < MIN_LOOKAHEAD
-- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
-- *    At least one byte has been read, or avail_in == 0; reads are
-- *    performed for at least two bytes (required for the zip translate_eol
-- *    option -- not supported here).
-- */
--local void fill_window(s)
--    deflate_state *s;
--{
--    unsigned n;
--    unsigned more;    /* Amount of free space at the end of the window. */
--    uInt wsize = s->w_size;
--
--    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
--
--    do {
--        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
--
--        /* Deal with !@#$% 64K limit: */
--        if (sizeof(int) <= 2) {
--            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
--                more = wsize;
--
--            } else if (more == (unsigned)(-1)) {
--                /* Very unlikely, but possible on 16 bit machine if
--                 * strstart == 0 && lookahead == 1 (input done a byte at time)
--                 */
--                more--;
--            }
--        }
--
--        /* If the window is almost full and there is insufficient lookahead,
--         * move the upper half to the lower one to make room in the upper half.
--         */
--        if (s->strstart >= wsize+MAX_DIST(s)) {
--
--            zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
--            s->match_start -= wsize;
--            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
--            s->block_start -= (long) wsize;
--            slide_hash(s);
--            more += wsize;
--        }
--        if (s->strm->avail_in == 0) break;
--
--        /* If there was no sliding:
--         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
--         *    more == window_size - lookahead - strstart
--         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
--         * => more >= window_size - 2*WSIZE + 2
--         * In the BIG_MEM or MMAP case (not yet supported),
--         *   window_size == input_size + MIN_LOOKAHEAD  &&
--         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
--         * Otherwise, window_size == 2*WSIZE so more >= 2.
--         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
--         */
--        Assert(more >= 2, "more < 2");
--
--        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
--        s->lookahead += n;
--
--        /* Initialize the hash value now that we have some input: */
--        if (s->lookahead + s->insert >= MIN_MATCH) {
--            uInt str = s->strstart - s->insert;
--            s->ins_h = s->window[str];
--            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
--#if MIN_MATCH != 3
--            Call UPDATE_HASH() MIN_MATCH-3 more times
--#endif
--            while (s->insert) {
--                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
--#ifndef FASTEST
--                s->prev[str & s->w_mask] = s->head[s->ins_h];
--#endif
--                s->head[s->ins_h] = (Pos)str;
--                str++;
--                s->insert--;
--                if (s->lookahead + s->insert < MIN_MATCH)
--                    break;
--            }
--        }
--        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
--         * but this is not important since only literal bytes will be emitted.
--         */
--
--    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
--
--    /* If the WIN_INIT bytes after the end of the current data have never been
--     * written, then zero those bytes in order to avoid memory check reports of
--     * the use of uninitialized (or uninitialised as Julian writes) bytes by
--     * the longest match routines.  Update the high water mark for the next
--     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
--     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
--     */
--    if (s->high_water < s->window_size) {
--        ulg curr = s->strstart + (ulg)(s->lookahead);
--        ulg init;
--
--        if (s->high_water < curr) {
--            /* Previous high water mark below current data -- zero WIN_INIT
--             * bytes or up to end of window, whichever is less.
--             */
--            init = s->window_size - curr;
--            if (init > WIN_INIT)
--                init = WIN_INIT;
--            zmemzero(s->window + curr, (unsigned)init);
--            s->high_water = curr + init;
--        }
--        else if (s->high_water < (ulg)curr + WIN_INIT) {
--            /* High water mark at or above current data, but below current data
--             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
--             * to end of window, whichever is less.
--             */
--            init = (ulg)curr + WIN_INIT - s->high_water;
--            if (init > s->window_size - s->high_water)
--                init = s->window_size - s->high_water;
--            zmemzero(s->window + s->high_water, (unsigned)init);
--            s->high_water += init;
--        }
--    }
--
--    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
--           "not enough room for search");
--}
--
--/* ===========================================================================
-- * Flush the current block, with given end-of-file flag.
-- * IN assertion: strstart is set to the end of the current match.
-- */
--#define FLUSH_BLOCK_ONLY(s, last) { \
--   _tr_flush_block(s, (s->block_start >= 0L ? \
--                   (charf *)&s->window[(unsigned)s->block_start] : \
--                   (charf *)Z_NULL), \
--                (ulg)((long)s->strstart - s->block_start), \
--                (last)); \
--   s->block_start = s->strstart; \
--   flush_pending(s->strm); \
--   Tracev((stderr,"[FLUSH]")); \
--}
--
--/* Same but force premature exit if necessary. */
--#define FLUSH_BLOCK(s, last) { \
--   FLUSH_BLOCK_ONLY(s, last); \
--   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
--}
--
--/* Maximum stored block length in deflate format (not including header). */
--#define MAX_STORED 65535
--
--/* Minimum of a and b. */
--#define MIN(a, b) ((a) > (b) ? (b) : (a))
--
--/* ===========================================================================
-- * Copy without compression as much as possible from the input stream, return
-- * the current block state.
-- *
-- * In case deflateParams() is used to later switch to a non-zero compression
-- * level, s->matches (otherwise unused when storing) keeps track of the number
-- * of hash table slides to perform. If s->matches is 1, then one hash table
-- * slide will be done when switching. If s->matches is 2, the maximum value
-- * allowed here, then the hash table will be cleared, since two or more slides
-- * is the same as a clear.
-- *
-- * deflate_stored() is written to minimize the number of times an input byte is
-- * copied. It is most efficient with large input and output buffers, which
-- * maximizes the opportunites to have a single copy from next_in to next_out.
-- */
--local block_state deflate_stored(s, flush)
--    deflate_state *s;
--    int flush;
--{
--    /* Smallest worthy block size when not flushing or finishing. By default
--     * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
--     * large input and output buffers, the stored block size will be larger.
--     */
--    unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
--
--    /* Copy as many min_block or larger stored blocks directly to next_out as
--     * possible. If flushing, copy the remaining available input to next_out as
--     * stored blocks, if there is enough space.
--     */
--    unsigned len, left, have, last = 0;
--    unsigned used = s->strm->avail_in;
--    do {
--        /* Set len to the maximum size block that we can copy directly with the
--         * available input data and output space. Set left to how much of that
--         * would be copied from what's left in the window.
--         */
--        len = MAX_STORED;       /* maximum deflate stored block length */
--        have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
--        if (s->strm->avail_out < have)          /* need room for header */
--            break;
--            /* maximum stored block length that will fit in avail_out: */
--        have = s->strm->avail_out - have;
--        left = s->strstart - s->block_start;    /* bytes left in window */
--        if (len > (ulg)left + s->strm->avail_in)
--            len = left + s->strm->avail_in;     /* limit len to the input */
--        if (len > have)
--            len = have;                         /* limit len to the output */
--
--        /* If the stored block would be less than min_block in length, or if
--         * unable to copy all of the available input when flushing, then try
--         * copying to the window and the pending buffer instead. Also don't
--         * write an empty block when flushing -- deflate() does that.
--         */
--        if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
--                                flush == Z_NO_FLUSH ||
--                                len != left + s->strm->avail_in))
--            break;
--
--        /* Make a dummy stored block in pending to get the header bytes,
--         * including any pending bits. This also updates the debugging counts.
--         */
--        last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
--        _tr_stored_block(s, (char *)0, 0L, last);
--
--        /* Replace the lengths in the dummy stored block with len. */
--        s->pending_buf[s->pending - 4] = len;
--        s->pending_buf[s->pending - 3] = len >> 8;
--        s->pending_buf[s->pending - 2] = ~len;
--        s->pending_buf[s->pending - 1] = ~len >> 8;
--
--        /* Write the stored block header bytes. */
--        flush_pending(s->strm);
--
--#ifdef ZLIB_DEBUG
--        /* Update debugging counts for the data about to be copied. */
--        s->compressed_len += len << 3;
--        s->bits_sent += len << 3;
--#endif
--
--        /* Copy uncompressed bytes from the window to next_out. */
--        if (left) {
--            if (left > len)
--                left = len;
--            zmemcpy(s->strm->next_out, s->window + s->block_start, left);
--            s->strm->next_out += left;
--            s->strm->avail_out -= left;
--            s->strm->total_out += left;
--            s->block_start += left;
--            len -= left;
--        }
--
--        /* Copy uncompressed bytes directly from next_in to next_out, updating
--         * the check value.
--         */
--        if (len) {
--            read_buf(s->strm, s->strm->next_out, len);
--            s->strm->next_out += len;
--            s->strm->avail_out -= len;
--            s->strm->total_out += len;
--        }
--    } while (last == 0);
--
--    /* Update the sliding window with the last s->w_size bytes of the copied
--     * data, or append all of the copied data to the existing window if less
--     * than s->w_size bytes were copied. Also update the number of bytes to
--     * insert in the hash tables, in the event that deflateParams() switches to
--     * a non-zero compression level.
--     */
--    used -= s->strm->avail_in;      /* number of input bytes directly copied */
--    if (used) {
--        /* If any input was used, then no unused input remains in the window,
--         * therefore s->block_start == s->strstart.
--         */
--        if (used >= s->w_size) {    /* supplant the previous history */
--            s->matches = 2;         /* clear hash */
--            zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
--            s->strstart = s->w_size;
--        }
--        else {
--            if (s->window_size - s->strstart <= used) {
--                /* Slide the window down. */
--                s->strstart -= s->w_size;
--                zmemcpy(s->window, s->window + s->w_size, s->strstart);
--                if (s->matches < 2)
--                    s->matches++;   /* add a pending slide_hash() */
--            }
--            zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
--            s->strstart += used;
--        }
--        s->block_start = s->strstart;
--        s->insert += MIN(used, s->w_size - s->insert);
--    }
--    if (s->high_water < s->strstart)
--        s->high_water = s->strstart;
--
--    /* If the last block was written to next_out, then done. */
--    if (last)
--        return finish_done;
--
--    /* If flushing and all input has been consumed, then done. */
--    if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
--        s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
--        return block_done;
--
--    /* Fill the window with any remaining input. */
--    have = s->window_size - s->strstart - 1;
--    if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
--        /* Slide the window down. */
--        s->block_start -= s->w_size;
--        s->strstart -= s->w_size;
--        zmemcpy(s->window, s->window + s->w_size, s->strstart);
--        if (s->matches < 2)
--            s->matches++;           /* add a pending slide_hash() */
--        have += s->w_size;          /* more space now */
--    }
--    if (have > s->strm->avail_in)
--        have = s->strm->avail_in;
--    if (have) {
--        read_buf(s->strm, s->window + s->strstart, have);
--        s->strstart += have;
--    }
--    if (s->high_water < s->strstart)
--        s->high_water = s->strstart;
--
--    /* There was not enough avail_out to write a complete worthy or flushed
--     * stored block to next_out. Write a stored block to pending instead, if we
--     * have enough input for a worthy block, or if flushing and there is enough
--     * room for the remaining input as a stored block in the pending buffer.
--     */
--    have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
--        /* maximum stored block length that will fit in pending: */
--    have = MIN(s->pending_buf_size - have, MAX_STORED);
--    min_block = MIN(have, s->w_size);
--    left = s->strstart - s->block_start;
--    if (left >= min_block ||
--        ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
--         s->strm->avail_in == 0 && left <= have)) {
--        len = MIN(left, have);
--        last = flush == Z_FINISH && s->strm->avail_in == 0 &&
--               len == left ? 1 : 0;
--        _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
--        s->block_start += len;
--        flush_pending(s->strm);
--    }
--
--    /* We've done all we can with the available input and output. */
--    return last ? finish_started : need_more;
--}
--
--/* ===========================================================================
-- * Compress as much as possible from the input stream, return the current
-- * block state.
-- * This function does not perform lazy evaluation of matches and inserts
-- * new strings in the dictionary only for unmatched strings or for short
-- * matches. It is used only for the fast compression options.
-- */
--local block_state deflate_fast(s, flush)
--    deflate_state *s;
--    int flush;
--{
--    IPos hash_head;       /* head of the hash chain */
--    int bflush;           /* set if current block must be flushed */
--
--    for (;;) {
--        /* Make sure that we always have enough lookahead, except
--         * at the end of the input file. We need MAX_MATCH bytes
--         * for the next match, plus MIN_MATCH bytes to insert the
--         * string following the next match.
--         */
--        if (s->lookahead < MIN_LOOKAHEAD) {
--            fill_window(s);
--            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
--                return need_more;
--            }
--            if (s->lookahead == 0) break; /* flush the current block */
--        }
--
--        /* Insert the string window[strstart .. strstart+2] in the
--         * dictionary, and set hash_head to the head of the hash chain:
--         */
--        hash_head = NIL;
--        if (s->lookahead >= MIN_MATCH) {
--            INSERT_STRING(s, s->strstart, hash_head);
--        }
--
--        /* Find the longest match, discarding those <= prev_length.
--         * At this point we have always match_length < MIN_MATCH
--         */
--        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
--            /* To simplify the code, we prevent matches with the string
--             * of window index 0 (in particular we have to avoid a match
--             * of the string with itself at the start of the input file).
--             */
--            s->match_length = longest_match (s, hash_head);
--            /* longest_match() sets match_start */
--        }
--        if (s->match_length >= MIN_MATCH) {
--            check_match(s, s->strstart, s->match_start, s->match_length);
--
--            _tr_tally_dist(s, s->strstart - s->match_start,
--                           s->match_length - MIN_MATCH, bflush);
--
--            s->lookahead -= s->match_length;
--
--            /* Insert new strings in the hash table only if the match length
--             * is not too large. This saves time but degrades compression.
--             */
--#ifndef FASTEST
--            if (s->match_length <= s->max_insert_length &&
--                s->lookahead >= MIN_MATCH) {
--                s->match_length--; /* string at strstart already in table */
--                do {
--                    s->strstart++;
--                    INSERT_STRING(s, s->strstart, hash_head);
--                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
--                     * always MIN_MATCH bytes ahead.
--                     */
--                } while (--s->match_length != 0);
--                s->strstart++;
--            } else
--#endif
--            {
--                s->strstart += s->match_length;
--                s->match_length = 0;
--                s->ins_h = s->window[s->strstart];
--                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
--#if MIN_MATCH != 3
--                Call UPDATE_HASH() MIN_MATCH-3 more times
--#endif
--                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
--                 * matter since it will be recomputed at next deflate call.
--                 */
--            }
--        } else {
--            /* No match, output a literal byte */
--            Tracevv((stderr,"%c", s->window[s->strstart]));
--            _tr_tally_lit (s, s->window[s->strstart], bflush);
--            s->lookahead--;
--            s->strstart++;
--        }
--        if (bflush) FLUSH_BLOCK(s, 0);
--    }
--    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
--    if (flush == Z_FINISH) {
--        FLUSH_BLOCK(s, 1);
--        return finish_done;
--    }
--    if (s->last_lit)
--        FLUSH_BLOCK(s, 0);
--    return block_done;
--}
--
--#ifndef FASTEST
--/* ===========================================================================
-- * Same as above, but achieves better compression. We use a lazy
-- * evaluation for matches: a match is finally adopted only if there is
-- * no better match at the next window position.
-- */
--local block_state deflate_slow(s, flush)
--    deflate_state *s;
--    int flush;
--{
--    IPos hash_head;          /* head of hash chain */
--    int bflush;              /* set if current block must be flushed */
--
--    /* Process the input block. */
--    for (;;) {
--        /* Make sure that we always have enough lookahead, except
--         * at the end of the input file. We need MAX_MATCH bytes
--         * for the next match, plus MIN_MATCH bytes to insert the
--         * string following the next match.
--         */
--        if (s->lookahead < MIN_LOOKAHEAD) {
--            fill_window(s);
--            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
--                return need_more;
--            }
--            if (s->lookahead == 0) break; /* flush the current block */
--        }
--
--        /* Insert the string window[strstart .. strstart+2] in the
--         * dictionary, and set hash_head to the head of the hash chain:
--         */
--        hash_head = NIL;
--        if (s->lookahead >= MIN_MATCH) {
--            INSERT_STRING(s, s->strstart, hash_head);
--        }
--
--        /* Find the longest match, discarding those <= prev_length.
--         */
--        s->prev_length = s->match_length, s->prev_match = s->match_start;
--        s->match_length = MIN_MATCH-1;
--
--        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
--            s->strstart - hash_head <= MAX_DIST(s)) {
--            /* To simplify the code, we prevent matches with the string
--             * of window index 0 (in particular we have to avoid a match
--             * of the string with itself at the start of the input file).
--             */
--            s->match_length = longest_match (s, hash_head);
--            /* longest_match() sets match_start */
--
--            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
--#if TOO_FAR <= 32767
--                || (s->match_length == MIN_MATCH &&
--                    s->strstart - s->match_start > TOO_FAR)
--#endif
--                )) {
--
--                /* If prev_match is also MIN_MATCH, match_start is garbage
--                 * but we will ignore the current match anyway.
--                 */
--                s->match_length = MIN_MATCH-1;
--            }
--        }
--        /* If there was a match at the previous step and the current
--         * match is not better, output the previous match:
--         */
--        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
--            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
--            /* Do not insert strings in hash table beyond this. */
--
--            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
--
--            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
--                           s->prev_length - MIN_MATCH, bflush);
--
--            /* Insert in hash table all strings up to the end of the match.
--             * strstart-1 and strstart are already inserted. If there is not
--             * enough lookahead, the last two strings are not inserted in
--             * the hash table.
--             */
--            s->lookahead -= s->prev_length-1;
--            s->prev_length -= 2;
--            do {
--                if (++s->strstart <= max_insert) {
--                    INSERT_STRING(s, s->strstart, hash_head);
--                }
--            } while (--s->prev_length != 0);
--            s->match_available = 0;
--            s->match_length = MIN_MATCH-1;
--            s->strstart++;
--
--            if (bflush) FLUSH_BLOCK(s, 0);
--
--        } else if (s->match_available) {
--            /* If there was no match at the previous position, output a
--             * single literal. If there was a match but the current match
--             * is longer, truncate the previous match to a single literal.
--             */
--            Tracevv((stderr,"%c", s->window[s->strstart-1]));
--            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
--            if (bflush) {
--                FLUSH_BLOCK_ONLY(s, 0);
--            }
--            s->strstart++;
--            s->lookahead--;
--            if (s->strm->avail_out == 0) return need_more;
--        } else {
--            /* There is no previous match to compare with, wait for
--             * the next step to decide.
--             */
--            s->match_available = 1;
--            s->strstart++;
--            s->lookahead--;
--        }
--    }
--    Assert (flush != Z_NO_FLUSH, "no flush?");
--    if (s->match_available) {
--        Tracevv((stderr,"%c", s->window[s->strstart-1]));
--        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
--        s->match_available = 0;
--    }
--    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
--    if (flush == Z_FINISH) {
--        FLUSH_BLOCK(s, 1);
--        return finish_done;
--    }
--    if (s->last_lit)
--        FLUSH_BLOCK(s, 0);
--    return block_done;
--}
--#endif /* FASTEST */
--
--/* ===========================================================================
-- * For Z_RLE, simply look for runs of bytes, generate matches only of distance
-- * one.  Do not maintain a hash table.  (It will be regenerated if this run of
-- * deflate switches away from Z_RLE.)
-- */
--local block_state deflate_rle(s, flush)
--    deflate_state *s;
--    int flush;
--{
--    int bflush;             /* set if current block must be flushed */
--    uInt prev;              /* byte at distance one to match */
--    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
--
--    for (;;) {
--        /* Make sure that we always have enough lookahead, except
--         * at the end of the input file. We need MAX_MATCH bytes
--         * for the longest run, plus one for the unrolled loop.
--         */
--        if (s->lookahead <= MAX_MATCH) {
--            fill_window(s);
--            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
--                return need_more;
--            }
--            if (s->lookahead == 0) break; /* flush the current block */
--        }
--
--        /* See how many times the previous byte repeats */
--        s->match_length = 0;
--        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
--            scan = s->window + s->strstart - 1;
--            prev = *scan;
--            if (prev == *++scan && prev == *++scan && prev == *++scan) {
--                strend = s->window + s->strstart + MAX_MATCH;
--                do {
--                } while (prev == *++scan && prev == *++scan &&
--                         prev == *++scan && prev == *++scan &&
--                         prev == *++scan && prev == *++scan &&
--                         prev == *++scan && prev == *++scan &&
--                         scan < strend);
--                s->match_length = MAX_MATCH - (uInt)(strend - scan);
--                if (s->match_length > s->lookahead)
--                    s->match_length = s->lookahead;
--            }
--            Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
--        }
--
--        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
--        if (s->match_length >= MIN_MATCH) {
--            check_match(s, s->strstart, s->strstart - 1, s->match_length);
--
--            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
--
--            s->lookahead -= s->match_length;
--            s->strstart += s->match_length;
--            s->match_length = 0;
--        } else {
--            /* No match, output a literal byte */
--            Tracevv((stderr,"%c", s->window[s->strstart]));
--            _tr_tally_lit (s, s->window[s->strstart], bflush);
--            s->lookahead--;
--            s->strstart++;
--        }
--        if (bflush) FLUSH_BLOCK(s, 0);
--    }
--    s->insert = 0;
--    if (flush == Z_FINISH) {
--        FLUSH_BLOCK(s, 1);
--        return finish_done;
--    }
--    if (s->last_lit)
--        FLUSH_BLOCK(s, 0);
--    return block_done;
--}
--
--/* ===========================================================================
-- * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
-- * (It will be regenerated if this run of deflate switches away from Huffman.)
-- */
--local block_state deflate_huff(s, flush)
--    deflate_state *s;
--    int flush;
--{
--    int bflush;             /* set if current block must be flushed */
--
--    for (;;) {
--        /* Make sure that we have a literal to write. */
--        if (s->lookahead == 0) {
--            fill_window(s);
--            if (s->lookahead == 0) {
--                if (flush == Z_NO_FLUSH)
--                    return need_more;
--                break;      /* flush the current block */
--            }
--        }
--
--        /* Output a literal byte */
--        s->match_length = 0;
--        Tracevv((stderr,"%c", s->window[s->strstart]));
--        _tr_tally_lit (s, s->window[s->strstart], bflush);
--        s->lookahead--;
--        s->strstart++;
--        if (bflush) FLUSH_BLOCK(s, 0);
--    }
--    s->insert = 0;
--    if (flush == Z_FINISH) {
--        FLUSH_BLOCK(s, 1);
--        return finish_done;
--    }
--    if (s->last_lit)
--        FLUSH_BLOCK(s, 0);
--    return block_done;
--}
diff --cc zlib/deflate.h
index 23ecdd312bc06eb41a40dce73358e62dea8772d2,23ecdd312bc06eb41a40dce73358e62dea8772d2..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,349 -1,349 +1,0 @@@
--/* deflate.h -- internal compression state
-- * Copyright (C) 1995-2016 Jean-loup Gailly
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* WARNING: this file should *not* be used by applications. It is
--   part of the implementation of the compression library and is
--   subject to change. Applications should only use zlib.h.
-- */
--
--/* @(#) $Id$ */
--
--#ifndef DEFLATE_H
--#define DEFLATE_H
--
--#include "zutil.h"
--
--/* define NO_GZIP when compiling if you want to disable gzip header and
--   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
--   the crc code when it is not needed.  For shared libraries, gzip encoding
--   should be left enabled. */
--#ifndef NO_GZIP
--#  define GZIP
--#endif
--
--/* ===========================================================================
-- * Internal compression state.
-- */
--
--#define LENGTH_CODES 29
--/* number of length codes, not counting the special END_BLOCK code */
--
--#define LITERALS  256
--/* number of literal bytes 0..255 */
--
--#define L_CODES (LITERALS+1+LENGTH_CODES)
--/* number of Literal or Length codes, including the END_BLOCK code */
--
--#define D_CODES   30
--/* number of distance codes */
--
--#define BL_CODES  19
--/* number of codes used to transfer the bit lengths */
--
--#define HEAP_SIZE (2*L_CODES+1)
--/* maximum heap size */
--
--#define MAX_BITS 15
--/* All codes must not exceed MAX_BITS bits */
--
--#define Buf_size 16
--/* size of bit buffer in bi_buf */
--
--#define INIT_STATE    42    /* zlib header -> BUSY_STATE */
--#ifdef GZIP
--#  define GZIP_STATE  57    /* gzip header -> BUSY_STATE | EXTRA_STATE */
--#endif
--#define EXTRA_STATE   69    /* gzip extra block -> NAME_STATE */
--#define NAME_STATE    73    /* gzip file name -> COMMENT_STATE */
--#define COMMENT_STATE 91    /* gzip comment -> HCRC_STATE */
--#define HCRC_STATE   103    /* gzip header CRC -> BUSY_STATE */
--#define BUSY_STATE   113    /* deflate -> FINISH_STATE */
--#define FINISH_STATE 666    /* stream complete */
--/* Stream status */
--
--
--/* Data structure describing a single value and its code string. */
--typedef struct ct_data_s {
--    union {
--        ush  freq;       /* frequency count */
--        ush  code;       /* bit string */
--    } fc;
--    union {
--        ush  dad;        /* father node in Huffman tree */
--        ush  len;        /* length of bit string */
--    } dl;
--} FAR ct_data;
--
--#define Freq fc.freq
--#define Code fc.code
--#define Dad  dl.dad
--#define Len  dl.len
--
--typedef struct static_tree_desc_s  static_tree_desc;
--
--typedef struct tree_desc_s {
--    ct_data *dyn_tree;           /* the dynamic tree */
--    int     max_code;            /* largest code with non zero frequency */
--    const static_tree_desc *stat_desc;  /* the corresponding static tree */
--} FAR tree_desc;
--
--typedef ush Pos;
--typedef Pos FAR Posf;
--typedef unsigned IPos;
--
--/* A Pos is an index in the character window. We use short instead of int to
-- * save space in the various tables. IPos is used only for parameter passing.
-- */
--
--typedef struct internal_state {
--    z_streamp strm;      /* pointer back to this zlib stream */
--    int   status;        /* as the name implies */
--    Bytef *pending_buf;  /* output still pending */
--    ulg   pending_buf_size; /* size of pending_buf */
--    Bytef *pending_out;  /* next pending byte to output to the stream */
--    ulg   pending;       /* nb of bytes in the pending buffer */
--    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
--    gz_headerp  gzhead;  /* gzip header information to write */
--    ulg   gzindex;       /* where in extra, name, or comment */
--    Byte  method;        /* can only be DEFLATED */
--    int   last_flush;    /* value of flush param for previous deflate call */
--
--                /* used by deflate.c: */
--
--    uInt  w_size;        /* LZ77 window size (32K by default) */
--    uInt  w_bits;        /* log2(w_size)  (8..16) */
--    uInt  w_mask;        /* w_size - 1 */
--
--    Bytef *window;
--    /* Sliding window. Input bytes are read into the second half of the window,
--     * and move to the first half later to keep a dictionary of at least wSize
--     * bytes. With this organization, matches are limited to a distance of
--     * wSize-MAX_MATCH bytes, but this ensures that IO is always
--     * performed with a length multiple of the block size. Also, it limits
--     * the window size to 64K, which is quite useful on MSDOS.
--     * To do: use the user input buffer as sliding window.
--     */
--
--    ulg window_size;
--    /* Actual size of window: 2*wSize, except when the user input buffer
--     * is directly used as sliding window.
--     */
--
--    Posf *prev;
--    /* Link to older string with same hash index. To limit the size of this
--     * array to 64K, this link is maintained only for the last 32K strings.
--     * An index in this array is thus a window index modulo 32K.
--     */
--
--    Posf *head; /* Heads of the hash chains or NIL. */
--
--    uInt  ins_h;          /* hash index of string to be inserted */
--    uInt  hash_size;      /* number of elements in hash table */
--    uInt  hash_bits;      /* log2(hash_size) */
--    uInt  hash_mask;      /* hash_size-1 */
--
--    uInt  hash_shift;
--    /* Number of bits by which ins_h must be shifted at each input
--     * step. It must be such that after MIN_MATCH steps, the oldest
--     * byte no longer takes part in the hash key, that is:
--     *   hash_shift * MIN_MATCH >= hash_bits
--     */
--
--    long block_start;
--    /* Window position at the beginning of the current output block. Gets
--     * negative when the window is moved backwards.
--     */
--
--    uInt match_length;           /* length of best match */
--    IPos prev_match;             /* previous match */
--    int match_available;         /* set if previous match exists */
--    uInt strstart;               /* start of string to insert */
--    uInt match_start;            /* start of matching string */
--    uInt lookahead;              /* number of valid bytes ahead in window */
--
--    uInt prev_length;
--    /* Length of the best match at previous step. Matches not greater than this
--     * are discarded. This is used in the lazy match evaluation.
--     */
--
--    uInt max_chain_length;
--    /* To speed up deflation, hash chains are never searched beyond this
--     * length.  A higher limit improves compression ratio but degrades the
--     * speed.
--     */
--
--    uInt max_lazy_match;
--    /* Attempt to find a better match only when the current match is strictly
--     * smaller than this value. This mechanism is used only for compression
--     * levels >= 4.
--     */
--#   define max_insert_length  max_lazy_match
--    /* Insert new strings in the hash table only if the match length is not
--     * greater than this length. This saves time but degrades compression.
--     * max_insert_length is used only for compression levels <= 3.
--     */
--
--    int level;    /* compression level (1..9) */
--    int strategy; /* favor or force Huffman coding*/
--
--    uInt good_match;
--    /* Use a faster search when the previous match is longer than this */
--
--    int nice_match; /* Stop searching when current match exceeds this */
--
--                /* used by trees.c: */
--    /* Didn't use ct_data typedef below to suppress compiler warning */
--    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
--    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
--    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
--
--    struct tree_desc_s l_desc;               /* desc. for literal tree */
--    struct tree_desc_s d_desc;               /* desc. for distance tree */
--    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
--
--    ush bl_count[MAX_BITS+1];
--    /* number of codes at each bit length for an optimal tree */
--
--    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
--    int heap_len;               /* number of elements in the heap */
--    int heap_max;               /* element of largest frequency */
--    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
--     * The same heap array is used to build all trees.
--     */
--
--    uch depth[2*L_CODES+1];
--    /* Depth of each subtree used as tie breaker for trees of equal frequency
--     */
--
--    uchf *l_buf;          /* buffer for literals or lengths */
--
--    uInt  lit_bufsize;
--    /* Size of match buffer for literals/lengths.  There are 4 reasons for
--     * limiting lit_bufsize to 64K:
--     *   - frequencies can be kept in 16 bit counters
--     *   - if compression is not successful for the first block, all input
--     *     data is still in the window so we can still emit a stored block even
--     *     when input comes from standard input.  (This can also be done for
--     *     all blocks if lit_bufsize is not greater than 32K.)
--     *   - if compression is not successful for a file smaller than 64K, we can
--     *     even emit a stored file instead of a stored block (saving 5 bytes).
--     *     This is applicable only for zip (not gzip or zlib).
--     *   - creating new Huffman trees less frequently may not provide fast
--     *     adaptation to changes in the input data statistics. (Take for
--     *     example a binary file with poorly compressible code followed by
--     *     a highly compressible string table.) Smaller buffer sizes give
--     *     fast adaptation but have of course the overhead of transmitting
--     *     trees more frequently.
--     *   - I can't count above 4
--     */
--
--    uInt last_lit;      /* running index in l_buf */
--
--    ushf *d_buf;
--    /* Buffer for distances. To simplify the code, d_buf and l_buf have
--     * the same number of elements. To use different lengths, an extra flag
--     * array would be necessary.
--     */
--
--    ulg opt_len;        /* bit length of current block with optimal trees */
--    ulg static_len;     /* bit length of current block with static trees */
--    uInt matches;       /* number of string matches in current block */
--    uInt insert;        /* bytes at end of window left to insert */
--
--#ifdef ZLIB_DEBUG
--    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
--    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
--#endif
--
--    ush bi_buf;
--    /* Output buffer. bits are inserted starting at the bottom (least
--     * significant bits).
--     */
--    int bi_valid;
--    /* Number of valid bits in bi_buf.  All bits above the last valid bit
--     * are always zero.
--     */
--
--    ulg high_water;
--    /* High water mark offset in window for initialized bytes -- bytes above
--     * this are set to zero in order to avoid memory check warnings when
--     * longest match routines access bytes past the input.  This is then
--     * updated to the new high water mark.
--     */
--
--} FAR deflate_state;
--
--/* Output a byte on the stream.
-- * IN assertion: there is enough room in pending_buf.
-- */
--#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);}
--
--
--#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
--/* Minimum amount of lookahead, except at the end of the input file.
-- * See deflate.c for comments about the MIN_MATCH+1.
-- */
--
--#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
--/* In order to simplify the code, particularly on 16 bit machines, match
-- * distances are limited to MAX_DIST instead of WSIZE.
-- */
--
--#define WIN_INIT MAX_MATCH
--/* Number of bytes after end of data in window to initialize in order to avoid
--   memory checker errors from longest match routines */
--
--        /* in trees.c */
--void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
--int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
--void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
--                        ulg stored_len, int last));
--void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
--void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
--void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
--                        ulg stored_len, int last));
--
--#define d_code(dist) \
--   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
--/* Mapping from a distance to a distance code. dist is the distance - 1 and
-- * must not have side effects. _dist_code[256] and _dist_code[257] are never
-- * used.
-- */
--
--#ifndef ZLIB_DEBUG
--/* Inline versions of _tr_tally for speed: */
--
--#if defined(GEN_TREES_H) || !defined(STDC)
--  extern uch ZLIB_INTERNAL _length_code[];
--  extern uch ZLIB_INTERNAL _dist_code[];
--#else
--  extern const uch ZLIB_INTERNAL _length_code[];
--  extern const uch ZLIB_INTERNAL _dist_code[];
--#endif
--
--# define _tr_tally_lit(s, c, flush) \
--  { uch cc = (c); \
--    s->d_buf[s->last_lit] = 0; \
--    s->l_buf[s->last_lit++] = cc; \
--    s->dyn_ltree[cc].Freq++; \
--    flush = (s->last_lit == s->lit_bufsize-1); \
--   }
--# define _tr_tally_dist(s, distance, length, flush) \
--  { uch len = (uch)(length); \
--    ush dist = (ush)(distance); \
--    s->d_buf[s->last_lit] = dist; \
--    s->l_buf[s->last_lit++] = len; \
--    dist--; \
--    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
--    s->dyn_dtree[d_code(dist)].Freq++; \
--    flush = (s->last_lit == s->lit_bufsize-1); \
--  }
--#else
--# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
--# define _tr_tally_dist(s, distance, length, flush) \
--              flush = _tr_tally(s, distance, length)
--#endif
--
--#endif /* DEFLATE_H */
diff --cc zlib/gzclose.c
index caeb99a3177f477d622870255a00ac2b72f10cad,caeb99a3177f477d622870255a00ac2b72f10cad..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,25 -1,25 +1,0 @@@
--/* gzclose.c -- zlib gzclose() function
-- * Copyright (C) 2004, 2010 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#include "gzguts.h"
--
--/* gzclose() is in a separate file so that it is linked in only if it is used.
--   That way the other gzclose functions can be used instead to avoid linking in
--   unneeded compression or decompression routines. */
--int ZEXPORT gzclose(file)
--    gzFile file;
--{
--#ifndef NO_GZCOMPRESS
--    gz_statep state;
--
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--
--    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);
--#else
--    return gzclose_r(file);
--#endif
--}
diff --cc zlib/gzguts.h
index 990a4d2514933709883a7d949ed52146675fe2c1,990a4d2514933709883a7d949ed52146675fe2c1..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,218 -1,218 +1,0 @@@
--/* gzguts.h -- zlib internal header definitions for gz* operations
-- * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#ifdef _LARGEFILE64_SOURCE
--#  ifndef _LARGEFILE_SOURCE
--#    define _LARGEFILE_SOURCE 1
--#  endif
--#  ifdef _FILE_OFFSET_BITS
--#    undef _FILE_OFFSET_BITS
--#  endif
--#endif
--
--#ifdef HAVE_HIDDEN
--#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
--#else
--#  define ZLIB_INTERNAL
--#endif
--
--#include <stdio.h>
--#include "zlib.h"
--#ifdef STDC
--#  include <string.h>
--#  include <stdlib.h>
--#  include <limits.h>
--#endif
--
--#ifndef _POSIX_SOURCE
--#  define _POSIX_SOURCE
--#endif
--#include <fcntl.h>
--
--#ifdef _WIN32
--#  include <stddef.h>
--#endif
--
--#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
--#  include <io.h>
--#endif
--
--#if defined(_WIN32) || defined(__CYGWIN__)
--#  define WIDECHAR
--#endif
--
--#ifdef WINAPI_FAMILY
--#  define open _open
--#  define read _read
--#  define write _write
--#  define close _close
--#endif
--
--#ifdef NO_DEFLATE       /* for compatibility with old definition */
--#  define NO_GZCOMPRESS
--#endif
--
--#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
--#  ifndef HAVE_VSNPRINTF
--#    define HAVE_VSNPRINTF
--#  endif
--#endif
--
--#if defined(__CYGWIN__)
--#  ifndef HAVE_VSNPRINTF
--#    define HAVE_VSNPRINTF
--#  endif
--#endif
--
--#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
--#  ifndef HAVE_VSNPRINTF
--#    define HAVE_VSNPRINTF
--#  endif
--#endif
--
--#ifndef HAVE_VSNPRINTF
--#  ifdef MSDOS
--/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
--   but for now we just assume it doesn't. */
--#    define NO_vsnprintf
--#  endif
--#  ifdef __TURBOC__
--#    define NO_vsnprintf
--#  endif
--#  ifdef WIN32
--/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
--#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
--#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
--#         define vsnprintf _vsnprintf
--#      endif
--#    endif
--#  endif
--#  ifdef __SASC
--#    define NO_vsnprintf
--#  endif
--#  ifdef VMS
--#    define NO_vsnprintf
--#  endif
--#  ifdef __OS400__
--#    define NO_vsnprintf
--#  endif
--#  ifdef __MVS__
--#    define NO_vsnprintf
--#  endif
--#endif
--
--/* unlike snprintf (which is required in C99), _snprintf does not guarantee
--   null termination of the result -- however this is only used in gzlib.c where
--   the result is assured to fit in the space provided */
--#if defined(_MSC_VER) && _MSC_VER < 1900
--#  define snprintf _snprintf
--#endif
--
--#ifndef local
--#  define local static
--#endif
--/* since "static" is used to mean two completely different things in C, we
--   define "local" for the non-static meaning of "static", for readability
--   (compile with -Dlocal if your debugger can't find static symbols) */
--
--/* gz* functions always use library allocation functions */
--#ifndef STDC
--  extern voidp  malloc OF((uInt size));
--  extern void   free   OF((voidpf ptr));
--#endif
--
--/* get errno and strerror definition */
--#if defined UNDER_CE
--#  include <windows.h>
--#  define zstrerror() gz_strwinerror((DWORD)GetLastError())
--#else
--#  ifndef NO_STRERROR
--#    include <errno.h>
--#    define zstrerror() strerror(errno)
--#  else
--#    define zstrerror() "stdio error (consult errno)"
--#  endif
--#endif
--
--/* provide prototypes for these when building zlib without LFS */
--#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
--    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
--    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
--    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
--    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
--#endif
--
--/* default memLevel */
--#if MAX_MEM_LEVEL >= 8
--#  define DEF_MEM_LEVEL 8
--#else
--#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
--#endif
--
--/* default i/o buffer size -- double this for output when reading (this and
--   twice this must be able to fit in an unsigned type) */
--#define GZBUFSIZE 8192
--
--/* gzip modes, also provide a little integrity check on the passed structure */
--#define GZ_NONE 0
--#define GZ_READ 7247
--#define GZ_WRITE 31153
--#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */
--
--/* values for gz_state how */
--#define LOOK 0      /* look for a gzip header */
--#define COPY 1      /* copy input directly */
--#define GZIP 2      /* decompress a gzip stream */
--
--/* internal gzip file state data structure */
--typedef struct {
--        /* exposed contents for gzgetc() macro */
--    struct gzFile_s x;      /* "x" for exposed */
--                            /* x.have: number of bytes available at x.next */
--                            /* x.next: next output data to deliver or write */
--                            /* x.pos: current position in uncompressed data */
--        /* used for both reading and writing */
--    int mode;               /* see gzip modes above */
--    int fd;                 /* file descriptor */
--    char *path;             /* path or fd for error messages */
--    unsigned size;          /* buffer size, zero if not allocated yet */
--    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
--    unsigned char *in;      /* input buffer (double-sized when writing) */
--    unsigned char *out;     /* output buffer (double-sized when reading) */
--    int direct;             /* 0 if processing gzip, 1 if transparent */
--        /* just for reading */
--    int how;                /* 0: get header, 1: copy, 2: decompress */
--    z_off64_t start;        /* where the gzip data started, for rewinding */
--    int eof;                /* true if end of input file reached */
--    int past;               /* true if read requested past end */
--        /* just for writing */
--    int level;              /* compression level */
--    int strategy;           /* compression strategy */
--        /* seek request */
--    z_off64_t skip;         /* amount to skip (already rewound if backwards) */
--    int seek;               /* true if seek request pending */
--        /* error information */
--    int err;                /* error code */
--    char *msg;              /* error message */
--        /* zlib inflate or deflate stream */
--    z_stream strm;          /* stream structure in-place (not a pointer) */
--} gz_state;
--typedef gz_state FAR *gz_statep;
--
--/* shared functions */
--void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));
--#if defined UNDER_CE
--char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));
--#endif
--
--/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
--   value -- needed when comparing unsigned to z_off64_t, which is signed
--   (possible z_off64_t types off_t, off64_t, and long are all signed) */
--#ifdef INT_MAX
--#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
--#else
--unsigned ZLIB_INTERNAL gz_intmax OF((void));
--#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
--#endif
diff --cc zlib/gzlib.c
index 4105e6aff92594fb9cfa557aa8349cea5a5d4a2b,4105e6aff92594fb9cfa557aa8349cea5a5d4a2b..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,637 -1,637 +1,0 @@@
--/* gzlib.c -- zlib functions common to reading and writing gzip files
-- * Copyright (C) 2004-2017 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#include "gzguts.h"
--
--#if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__)
--#  define LSEEK _lseeki64
--#else
--#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
--#  define LSEEK lseek64
--#else
--#  define LSEEK lseek
--#endif
--#endif
--
--/* Local functions */
--local void gz_reset OF((gz_statep));
--local gzFile gz_open OF((const void *, int, const char *));
--
--#if defined UNDER_CE
--
--/* Map the Windows error number in ERROR to a locale-dependent error message
--   string and return a pointer to it.  Typically, the values for ERROR come
--   from GetLastError.
--
--   The string pointed to shall not be modified by the application, but may be
--   overwritten by a subsequent call to gz_strwinerror
--
--   The gz_strwinerror function does not change the current setting of
--   GetLastError. */
--char ZLIB_INTERNAL *gz_strwinerror (error)
--     DWORD error;
--{
--    static char buf[1024];
--
--    wchar_t *msgbuf;
--    DWORD lasterr = GetLastError();
--    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
--        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
--        NULL,
--        error,
--        0, /* Default language */
--        (LPVOID)&msgbuf,
--        0,
--        NULL);
--    if (chars != 0) {
--        /* If there is an \r\n appended, zap it.  */
--        if (chars >= 2
--            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
--            chars -= 2;
--            msgbuf[chars] = 0;
--        }
--
--        if (chars > sizeof (buf) - 1) {
--            chars = sizeof (buf) - 1;
--            msgbuf[chars] = 0;
--        }
--
--        wcstombs(buf, msgbuf, chars + 1);
--        LocalFree(msgbuf);
--    }
--    else {
--        sprintf(buf, "unknown win32 error (%ld)", error);
--    }
--
--    SetLastError(lasterr);
--    return buf;
--}
--
--#endif /* UNDER_CE */
--
--/* Reset gzip file state */
--local void gz_reset(state)
--    gz_statep state;
--{
--    state->x.have = 0;              /* no output data available */
--    if (state->mode == GZ_READ) {   /* for reading ... */
--        state->eof = 0;             /* not at end of file */
--        state->past = 0;            /* have not read past end yet */
--        state->how = LOOK;          /* look for gzip header */
--    }
--    state->seek = 0;                /* no seek request pending */
--    gz_error(state, Z_OK, NULL);    /* clear error */
--    state->x.pos = 0;               /* no uncompressed data yet */
--    state->strm.avail_in = 0;       /* no input data yet */
--}
--
--/* Open a gzip file either by name or file descriptor. */
--local gzFile gz_open(path, fd, mode)
--    const void *path;
--    int fd;
--    const char *mode;
--{
--    gz_statep state;
--    z_size_t len;
--    int oflag;
--#ifdef O_CLOEXEC
--    int cloexec = 0;
--#endif
--#ifdef O_EXCL
--    int exclusive = 0;
--#endif
--
--    /* check input */
--    if (path == NULL)
--        return NULL;
--
--    /* allocate gzFile structure to return */
--    state = (gz_statep)malloc(sizeof(gz_state));
--    if (state == NULL)
--        return NULL;
--    state->size = 0;            /* no buffers allocated yet */
--    state->want = GZBUFSIZE;    /* requested buffer size */
--    state->msg = NULL;          /* no error message yet */
--
--    /* interpret mode */
--    state->mode = GZ_NONE;
--    state->level = Z_DEFAULT_COMPRESSION;
--    state->strategy = Z_DEFAULT_STRATEGY;
--    state->direct = 0;
--    while (*mode) {
--        if (*mode >= '0' && *mode <= '9')
--            state->level = *mode - '0';
--        else
--            switch (*mode) {
--            case 'r':
--                state->mode = GZ_READ;
--                break;
--#ifndef NO_GZCOMPRESS
--            case 'w':
--                state->mode = GZ_WRITE;
--                break;
--            case 'a':
--                state->mode = GZ_APPEND;
--                break;
--#endif
--            case '+':       /* can't read and write at the same time */
--                free(state);
--                return NULL;
--            case 'b':       /* ignore -- will request binary anyway */
--                break;
--#ifdef O_CLOEXEC
--            case 'e':
--                cloexec = 1;
--                break;
--#endif
--#ifdef O_EXCL
--            case 'x':
--                exclusive = 1;
--                break;
--#endif
--            case 'f':
--                state->strategy = Z_FILTERED;
--                break;
--            case 'h':
--                state->strategy = Z_HUFFMAN_ONLY;
--                break;
--            case 'R':
--                state->strategy = Z_RLE;
--                break;
--            case 'F':
--                state->strategy = Z_FIXED;
--                break;
--            case 'T':
--                state->direct = 1;
--                break;
--            default:        /* could consider as an error, but just ignore */
--                ;
--            }
--        mode++;
--    }
--
--    /* must provide an "r", "w", or "a" */
--    if (state->mode == GZ_NONE) {
--        free(state);
--        return NULL;
--    }
--
--    /* can't force transparent read */
--    if (state->mode == GZ_READ) {
--        if (state->direct) {
--            free(state);
--            return NULL;
--        }
--        state->direct = 1;      /* for empty file */
--    }
--
--    /* save the path name for error messages */
--#ifdef WIDECHAR
--    if (fd == -2) {
--        len = wcstombs(NULL, path, 0);
--        if (len == (z_size_t)-1)
--            len = 0;
--    }
--    else
--#endif
--        len = strlen((const char *)path);
--    state->path = (char *)malloc(len + 1);
--    if (state->path == NULL) {
--        free(state);
--        return NULL;
--    }
--#ifdef WIDECHAR
--    if (fd == -2)
--        if (len)
--            wcstombs(state->path, path, len + 1);
--        else
--            *(state->path) = 0;
--    else
--#endif
--#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
--        (void)snprintf(state->path, len + 1, "%s", (const char *)path);
--#else
--        strcpy(state->path, path);
--#endif
--
--    /* compute the flags for open() */
--    oflag =
--#ifdef O_LARGEFILE
--        O_LARGEFILE |
--#endif
--#ifdef O_BINARY
--        O_BINARY |
--#endif
--#ifdef O_CLOEXEC
--        (cloexec ? O_CLOEXEC : 0) |
--#endif
--        (state->mode == GZ_READ ?
--         O_RDONLY :
--         (O_WRONLY | O_CREAT |
--#ifdef O_EXCL
--          (exclusive ? O_EXCL : 0) |
--#endif
--          (state->mode == GZ_WRITE ?
--           O_TRUNC :
--           O_APPEND)));
--
--    /* open the file with the appropriate flags (or just use fd) */
--    state->fd = fd > -1 ? fd : (
--#ifdef WIDECHAR
--        fd == -2 ? _wopen(path, oflag, 0666) :
--#endif
--        open((const char *)path, oflag, 0666));
--    if (state->fd == -1) {
--        free(state->path);
--        free(state);
--        return NULL;
--    }
--    if (state->mode == GZ_APPEND) {
--        LSEEK(state->fd, 0, SEEK_END);  /* so gzoffset() is correct */
--        state->mode = GZ_WRITE;         /* simplify later checks */
--    }
--
--    /* save the current position for rewinding (only if reading) */
--    if (state->mode == GZ_READ) {
--        state->start = LSEEK(state->fd, 0, SEEK_CUR);
--        if (state->start == -1) state->start = 0;
--    }
--
--    /* initialize stream */
--    gz_reset(state);
--
--    /* return stream */
--    return (gzFile)state;
--}
--
--/* -- see zlib.h -- */
--gzFile ZEXPORT gzopen(path, mode)
--    const char *path;
--    const char *mode;
--{
--    return gz_open(path, -1, mode);
--}
--
--/* -- see zlib.h -- */
--gzFile ZEXPORT gzopen64(path, mode)
--    const char *path;
--    const char *mode;
--{
--    return gz_open(path, -1, mode);
--}
--
--/* -- see zlib.h -- */
--gzFile ZEXPORT gzdopen(fd, mode)
--    int fd;
--    const char *mode;
--{
--    char *path;         /* identifier for error messages */
--    gzFile gz;
--
--    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
--        return NULL;
--#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
--    (void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd);
--#else
--    sprintf(path, "<fd:%d>", fd);   /* for debugging */
--#endif
--    gz = gz_open(path, fd, mode);
--    free(path);
--    return gz;
--}
--
--/* -- see zlib.h -- */
--#ifdef WIDECHAR
--gzFile ZEXPORT gzopen_w(path, mode)
--    const wchar_t *path;
--    const char *mode;
--{
--    return gz_open(path, -2, mode);
--}
--#endif
--
--/* -- see zlib.h -- */
--int ZEXPORT gzbuffer(file, size)
--    gzFile file;
--    unsigned size;
--{
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return -1;
--
--    /* make sure we haven't already allocated memory */
--    if (state->size != 0)
--        return -1;
--
--    /* check and set requested size */
--    if ((size << 1) < size)
--        return -1;              /* need to be able to double it */
--    if (size < 2)
--        size = 2;               /* need two bytes to check magic header */
--    state->want = size;
--    return 0;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzrewind(file)
--    gzFile file;
--{
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--
--    /* check that we're reading and that there's no error */
--    if (state->mode != GZ_READ ||
--            (state->err != Z_OK && state->err != Z_BUF_ERROR))
--        return -1;
--
--    /* back up and start over */
--    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
--        return -1;
--    gz_reset(state);
--    return 0;
--}
--
--/* -- see zlib.h -- */
--z_off64_t ZEXPORT gzseek64(file, offset, whence)
--    gzFile file;
--    z_off64_t offset;
--    int whence;
--{
--    unsigned n;
--    z_off64_t ret;
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return -1;
--
--    /* check that there's no error */
--    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
--        return -1;
--
--    /* can only seek from start or relative to current position */
--    if (whence != SEEK_SET && whence != SEEK_CUR)
--        return -1;
--
--    /* normalize offset to a SEEK_CUR specification */
--    if (whence == SEEK_SET)
--        offset -= state->x.pos;
--    else if (state->seek)
--        offset += state->skip;
--    state->seek = 0;
--
--    /* if within raw area while reading, just go there */
--    if (state->mode == GZ_READ && state->how == COPY &&
--            state->x.pos + offset >= 0) {
--        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);
--        if (ret == -1)
--            return -1;
--        state->x.have = 0;
--        state->eof = 0;
--        state->past = 0;
--        state->seek = 0;
--        gz_error(state, Z_OK, NULL);
--        state->strm.avail_in = 0;
--        state->x.pos += offset;
--        return state->x.pos;
--    }
--
--    /* calculate skip amount, rewinding if needed for back seek when reading */
--    if (offset < 0) {
--        if (state->mode != GZ_READ)         /* writing -- can't go backwards */
--            return -1;
--        offset += state->x.pos;
--        if (offset < 0)                     /* before start of file! */
--            return -1;
--        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
--            return -1;
--    }
--
--    /* if reading, skip what's in output buffer (one less gzgetc() check) */
--    if (state->mode == GZ_READ) {
--        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
--            (unsigned)offset : state->x.have;
--        state->x.have -= n;
--        state->x.next += n;
--        state->x.pos += n;
--        offset -= n;
--    }
--
--    /* request skip (if not zero) */
--    if (offset) {
--        state->seek = 1;
--        state->skip = offset;
--    }
--    return state->x.pos + offset;
--}
--
--/* -- see zlib.h -- */
--z_off_t ZEXPORT gzseek(file, offset, whence)
--    gzFile file;
--    z_off_t offset;
--    int whence;
--{
--    z_off64_t ret;
--
--    ret = gzseek64(file, (z_off64_t)offset, whence);
--    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
--}
--
--/* -- see zlib.h -- */
--z_off64_t ZEXPORT gztell64(file)
--    gzFile file;
--{
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return -1;
--
--    /* return position */
--    return state->x.pos + (state->seek ? state->skip : 0);
--}
--
--/* -- see zlib.h -- */
--z_off_t ZEXPORT gztell(file)
--    gzFile file;
--{
--    z_off64_t ret;
--
--    ret = gztell64(file);
--    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
--}
--
--/* -- see zlib.h -- */
--z_off64_t ZEXPORT gzoffset64(file)
--    gzFile file;
--{
--    z_off64_t offset;
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return -1;
--
--    /* compute and return effective offset in file */
--    offset = LSEEK(state->fd, 0, SEEK_CUR);
--    if (offset == -1)
--        return -1;
--    if (state->mode == GZ_READ)             /* reading */
--        offset -= state->strm.avail_in;     /* don't count buffered input */
--    return offset;
--}
--
--/* -- see zlib.h -- */
--z_off_t ZEXPORT gzoffset(file)
--    gzFile file;
--{
--    z_off64_t ret;
--
--    ret = gzoffset64(file);
--    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzeof(file)
--    gzFile file;
--{
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return 0;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return 0;
--
--    /* return end-of-file state */
--    return state->mode == GZ_READ ? state->past : 0;
--}
--
--/* -- see zlib.h -- */
--const char * ZEXPORT gzerror(file, errnum)
--    gzFile file;
--    int *errnum;
--{
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return NULL;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return NULL;
--
--    /* return error information */
--    if (errnum != NULL)
--        *errnum = state->err;
--    return state->err == Z_MEM_ERROR ? "out of memory" :
--                                       (state->msg == NULL ? "" : state->msg);
--}
--
--/* -- see zlib.h -- */
--void ZEXPORT gzclearerr(file)
--    gzFile file;
--{
--    gz_statep state;
--
--    /* get internal structure and check integrity */
--    if (file == NULL)
--        return;
--    state = (gz_statep)file;
--    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
--        return;
--
--    /* clear error and end-of-file */
--    if (state->mode == GZ_READ) {
--        state->eof = 0;
--        state->past = 0;
--    }
--    gz_error(state, Z_OK, NULL);
--}
--
--/* Create an error message in allocated memory and set state->err and
--   state->msg accordingly.  Free any previous error message already there.  Do
--   not try to free or allocate space if the error is Z_MEM_ERROR (out of
--   memory).  Simply save the error message as a static string.  If there is an
--   allocation failure constructing the error message, then convert the error to
--   out of memory. */
--void ZLIB_INTERNAL gz_error(state, err, msg)
--    gz_statep state;
--    int err;
--    const char *msg;
--{
--    /* free previously allocated message and clear */
--    if (state->msg != NULL) {
--        if (state->err != Z_MEM_ERROR)
--            free(state->msg);
--        state->msg = NULL;
--    }
--
--    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
--    if (err != Z_OK && err != Z_BUF_ERROR)
--        state->x.have = 0;
--
--    /* set error code, and if no message, then done */
--    state->err = err;
--    if (msg == NULL)
--        return;
--
--    /* for an out of memory error, return literal string when requested */
--    if (err == Z_MEM_ERROR)
--        return;
--
--    /* construct error message with path */
--    if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
--            NULL) {
--        state->err = Z_MEM_ERROR;
--        return;
--    }
--#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
--    (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
--                   "%s%s%s", state->path, ": ", msg);
--#else
--    strcpy(state->msg, state->path);
--    strcat(state->msg, ": ");
--    strcat(state->msg, msg);
--#endif
--}
--
--#ifndef INT_MAX
--/* portably return maximum value for an int (when limits.h presumed not
--   available) -- we need to do this to cover cases where 2's complement not
--   used, since C standard permits 1's complement and sign-bit representations,
--   otherwise we could just use ((unsigned)-1) >> 1 */
--unsigned ZLIB_INTERNAL gz_intmax()
--{
--    unsigned p, q;
--
--    p = 1;
--    do {
--        q = p;
--        p <<= 1;
--        p++;
--    } while (p > q);
--    return q >> 1;
--}
--#endif
diff --cc zlib/gzread.c
index 956b91ea7d9e2a7cd554f7d6561142509b655244,956b91ea7d9e2a7cd554f7d6561142509b655244..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,654 -1,654 +1,0 @@@
--/* gzread.c -- zlib functions for reading gzip files
-- * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#include "gzguts.h"
--
--/* Local functions */
--local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
--local int gz_avail OF((gz_statep));
--local int gz_look OF((gz_statep));
--local int gz_decomp OF((gz_statep));
--local int gz_fetch OF((gz_statep));
--local int gz_skip OF((gz_statep, z_off64_t));
--local z_size_t gz_read OF((gz_statep, voidp, z_size_t));
--
--/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
--   state->fd, and update state->eof, state->err, and state->msg as appropriate.
--   This function needs to loop on read(), since read() is not guaranteed to
--   read the number of bytes requested, depending on the type of descriptor. */
--local int gz_load(state, buf, len, have)
--    gz_statep state;
--    unsigned char *buf;
--    unsigned len;
--    unsigned *have;
--{
--    int ret;
--    unsigned get, max = ((unsigned)-1 >> 2) + 1;
--
--    *have = 0;
--    do {
--        get = len - *have;
--        if (get > max)
--            get = max;
--        ret = read(state->fd, buf + *have, get);
--        if (ret <= 0)
--            break;
--        *have += (unsigned)ret;
--    } while (*have < len);
--    if (ret < 0) {
--        gz_error(state, Z_ERRNO, zstrerror());
--        return -1;
--    }
--    if (ret == 0)
--        state->eof = 1;
--    return 0;
--}
--
--/* Load up input buffer and set eof flag if last data loaded -- return -1 on
--   error, 0 otherwise.  Note that the eof flag is set when the end of the input
--   file is reached, even though there may be unused data in the buffer.  Once
--   that data has been used, no more attempts will be made to read the file.
--   If strm->avail_in != 0, then the current data is moved to the beginning of
--   the input buffer, and then the remainder of the buffer is loaded with the
--   available data from the input file. */
--local int gz_avail(state)
--    gz_statep state;
--{
--    unsigned got;
--    z_streamp strm = &(state->strm);
--
--    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
--        return -1;
--    if (state->eof == 0) {
--        if (strm->avail_in) {       /* copy what's there to the start */
--            unsigned char *p = state->in;
--            unsigned const char *q = strm->next_in;
--            unsigned n = strm->avail_in;
--            do {
--                *p++ = *q++;
--            } while (--n);
--        }
--        if (gz_load(state, state->in + strm->avail_in,
--                    state->size - strm->avail_in, &got) == -1)
--            return -1;
--        strm->avail_in += got;
--        strm->next_in = state->in;
--    }
--    return 0;
--}
--
--/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.
--   If this is the first time in, allocate required memory.  state->how will be
--   left unchanged if there is no more input data available, will be set to COPY
--   if there is no gzip header and direct copying will be performed, or it will
--   be set to GZIP for decompression.  If direct copying, then leftover input
--   data from the input buffer will be copied to the output buffer.  In that
--   case, all further file reads will be directly to either the output buffer or
--   a user buffer.  If decompressing, the inflate state will be initialized.
--   gz_look() will return 0 on success or -1 on failure. */
--local int gz_look(state)
--    gz_statep state;
--{
--    z_streamp strm = &(state->strm);
--
--    /* allocate read buffers and inflate memory */
--    if (state->size == 0) {
--        /* allocate buffers */
--        state->in = (unsigned char *)malloc(state->want);
--        state->out = (unsigned char *)malloc(state->want << 1);
--        if (state->in == NULL || state->out == NULL) {
--            free(state->out);
--            free(state->in);
--            gz_error(state, Z_MEM_ERROR, "out of memory");
--            return -1;
--        }
--        state->size = state->want;
--
--        /* allocate inflate memory */
--        state->strm.zalloc = Z_NULL;
--        state->strm.zfree = Z_NULL;
--        state->strm.opaque = Z_NULL;
--        state->strm.avail_in = 0;
--        state->strm.next_in = Z_NULL;
--        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */
--            free(state->out);
--            free(state->in);
--            state->size = 0;
--            gz_error(state, Z_MEM_ERROR, "out of memory");
--            return -1;
--        }
--    }
--
--    /* get at least the magic bytes in the input buffer */
--    if (strm->avail_in < 2) {
--        if (gz_avail(state) == -1)
--            return -1;
--        if (strm->avail_in == 0)
--            return 0;
--    }
--
--    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
--       a logical dilemma here when considering the case of a partially written
--       gzip file, to wit, if a single 31 byte is written, then we cannot tell
--       whether this is a single-byte file, or just a partially written gzip
--       file -- for here we assume that if a gzip file is being written, then
--       the header will be written in a single operation, so that reading a
--       single byte is sufficient indication that it is not a gzip file) */
--    if (strm->avail_in > 1 &&
--            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
--        inflateReset(strm);
--        state->how = GZIP;
--        state->direct = 0;
--        return 0;
--    }
--
--    /* no gzip header -- if we were decoding gzip before, then this is trailing
--       garbage.  Ignore the trailing garbage and finish. */
--    if (state->direct == 0) {
--        strm->avail_in = 0;
--        state->eof = 1;
--        state->x.have = 0;
--        return 0;
--    }
--
--    /* doing raw i/o, copy any leftover input to output -- this assumes that
--       the output buffer is larger than the input buffer, which also assures
--       space for gzungetc() */
--    state->x.next = state->out;
--    if (strm->avail_in) {
--        memcpy(state->x.next, strm->next_in, strm->avail_in);
--        state->x.have = strm->avail_in;
--        strm->avail_in = 0;
--    }
--    state->how = COPY;
--    state->direct = 1;
--    return 0;
--}
--
--/* Decompress from input to the provided next_out and avail_out in the state.
--   On return, state->x.have and state->x.next point to the just decompressed
--   data.  If the gzip stream completes, state->how is reset to LOOK to look for
--   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
--   on success, -1 on failure. */
--local int gz_decomp(state)
--    gz_statep state;
--{
--    int ret = Z_OK;
--    unsigned had;
--    z_streamp strm = &(state->strm);
--
--    /* fill output buffer up to end of deflate stream */
--    had = strm->avail_out;
--    do {
--        /* get more input for inflate() */
--        if (strm->avail_in == 0 && gz_avail(state) == -1)
--            return -1;
--        if (strm->avail_in == 0) {
--            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
--            break;
--        }
--
--        /* decompress and handle errors */
--        ret = inflate(strm, Z_NO_FLUSH);
--        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
--            gz_error(state, Z_STREAM_ERROR,
--                     "internal error: inflate stream corrupt");
--            return -1;
--        }
--        if (ret == Z_MEM_ERROR) {
--            gz_error(state, Z_MEM_ERROR, "out of memory");
--            return -1;
--        }
--        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
--            gz_error(state, Z_DATA_ERROR,
--                     strm->msg == NULL ? "compressed data error" : strm->msg);
--            return -1;
--        }
--    } while (strm->avail_out && ret != Z_STREAM_END);
--
--    /* update available output */
--    state->x.have = had - strm->avail_out;
--    state->x.next = strm->next_out - state->x.have;
--
--    /* if the gzip stream completed successfully, look for another */
--    if (ret == Z_STREAM_END)
--        state->how = LOOK;
--
--    /* good decompression */
--    return 0;
--}
--
--/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
--   Data is either copied from the input file or decompressed from the input
--   file depending on state->how.  If state->how is LOOK, then a gzip header is
--   looked for to determine whether to copy or decompress.  Returns -1 on error,
--   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the
--   end of the input file has been reached and all data has been processed.  */
--local int gz_fetch(state)
--    gz_statep state;
--{
--    z_streamp strm = &(state->strm);
--
--    do {
--        switch(state->how) {
--        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
--            if (gz_look(state) == -1)
--                return -1;
--            if (state->how == LOOK)
--                return 0;
--            break;
--        case COPY:      /* -> COPY */
--            if (gz_load(state, state->out, state->size << 1, &(state->x.have))
--                    == -1)
--                return -1;
--            state->x.next = state->out;
--            return 0;
--        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */
--            strm->avail_out = state->size << 1;
--            strm->next_out = state->out;
--            if (gz_decomp(state) == -1)
--                return -1;
--        }
--    } while (state->x.have == 0 && (!state->eof || strm->avail_in));
--    return 0;
--}
--
--/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
--local int gz_skip(state, len)
--    gz_statep state;
--    z_off64_t len;
--{
--    unsigned n;
--
--    /* skip over len bytes or reach end-of-file, whichever comes first */
--    while (len)
--        /* skip over whatever is in output buffer */
--        if (state->x.have) {
--            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
--                (unsigned)len : state->x.have;
--            state->x.have -= n;
--            state->x.next += n;
--            state->x.pos += n;
--            len -= n;
--        }
--
--        /* output buffer empty -- return if we're at the end of the input */
--        else if (state->eof && state->strm.avail_in == 0)
--            break;
--
--        /* need more data to skip -- load up output buffer */
--        else {
--            /* get more output, looking for header if required */
--            if (gz_fetch(state) == -1)
--                return -1;
--        }
--    return 0;
--}
--
--/* Read len bytes into buf from file, or less than len up to the end of the
--   input.  Return the number of bytes read.  If zero is returned, either the
--   end of file was reached, or there was an error.  state->err must be
--   consulted in that case to determine which. */
--local z_size_t gz_read(state, buf, len)
--    gz_statep state;
--    voidp buf;
--    z_size_t len;
--{
--    z_size_t got;
--    unsigned n;
--
--    /* if len is zero, avoid unnecessary operations */
--    if (len == 0)
--        return 0;
--
--    /* process a skip request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_skip(state, state->skip) == -1)
--            return 0;
--    }
--
--    /* get len bytes to buf, or less than len if at the end */
--    got = 0;
--    do {
--        /* set n to the maximum amount of len that fits in an unsigned int */
--        n = -1;
--        if (n > len)
--            n = len;
--
--        /* first just try copying data from the output buffer */
--        if (state->x.have) {
--            if (state->x.have < n)
--                n = state->x.have;
--            memcpy(buf, state->x.next, n);
--            state->x.next += n;
--            state->x.have -= n;
--        }
--
--        /* output buffer empty -- return if we're at the end of the input */
--        else if (state->eof && state->strm.avail_in == 0) {
--            state->past = 1;        /* tried to read past end */
--            break;
--        }
--
--        /* need output data -- for small len or new stream load up our output
--           buffer */
--        else if (state->how == LOOK || n < (state->size << 1)) {
--            /* get more output, looking for header if required */
--            if (gz_fetch(state) == -1)
--                return 0;
--            continue;       /* no progress yet -- go back to copy above */
--            /* the copy above assures that we will leave with space in the
--               output buffer, allowing at least one gzungetc() to succeed */
--        }
--
--        /* large len -- read directly into user buffer */
--        else if (state->how == COPY) {      /* read directly */
--            if (gz_load(state, (unsigned char *)buf, n, &n) == -1)
--                return 0;
--        }
--
--        /* large len -- decompress directly into user buffer */
--        else {  /* state->how == GZIP */
--            state->strm.avail_out = n;
--            state->strm.next_out = (unsigned char *)buf;
--            if (gz_decomp(state) == -1)
--                return 0;
--            n = state->x.have;
--            state->x.have = 0;
--        }
--
--        /* update progress */
--        len -= n;
--        buf = (char *)buf + n;
--        got += n;
--        state->x.pos += n;
--    } while (len);
--
--    /* return number of bytes read into user buffer */
--    return got;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzread(file, buf, len)
--    gzFile file;
--    voidp buf;
--    unsigned len;
--{
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--
--    /* check that we're reading and that there's no (serious) error */
--    if (state->mode != GZ_READ ||
--            (state->err != Z_OK && state->err != Z_BUF_ERROR))
--        return -1;
--
--    /* since an int is returned, make sure len fits in one, otherwise return
--       with an error (this avoids a flaw in the interface) */
--    if ((int)len < 0) {
--        gz_error(state, Z_STREAM_ERROR, "request does not fit in an int");
--        return -1;
--    }
--
--    /* read len or fewer bytes to buf */
--    len = gz_read(state, buf, len);
--
--    /* check for an error */
--    if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR)
--        return -1;
--
--    /* return the number of bytes read (this is assured to fit in an int) */
--    return (int)len;
--}
--
--/* -- see zlib.h -- */
--z_size_t ZEXPORT gzfread(buf, size, nitems, file)
--    voidp buf;
--    z_size_t size;
--    z_size_t nitems;
--    gzFile file;
--{
--    z_size_t len;
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return 0;
--    state = (gz_statep)file;
--
--    /* check that we're reading and that there's no (serious) error */
--    if (state->mode != GZ_READ ||
--            (state->err != Z_OK && state->err != Z_BUF_ERROR))
--        return 0;
--
--    /* compute bytes to read -- error on overflow */
--    len = nitems * size;
--    if (size && len / size != nitems) {
--        gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");
--        return 0;
--    }
--
--    /* read len or fewer bytes to buf, return the number of full items read */
--    return len ? gz_read(state, buf, len) / size : 0;
--}
--
--/* -- see zlib.h -- */
--#ifdef Z_PREFIX_SET
--#  undef z_gzgetc
--#else
--#  undef gzgetc
--#endif
--int ZEXPORT gzgetc(file)
--    gzFile file;
--{
--    int ret;
--    unsigned char buf[1];
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--
--    /* check that we're reading and that there's no (serious) error */
--    if (state->mode != GZ_READ ||
--        (state->err != Z_OK && state->err != Z_BUF_ERROR))
--        return -1;
--
--    /* try output buffer (no need to check for skip request) */
--    if (state->x.have) {
--        state->x.have--;
--        state->x.pos++;
--        return *(state->x.next)++;
--    }
--
--    /* nothing there -- try gz_read() */
--    ret = gz_read(state, buf, 1);
--    return ret < 1 ? -1 : buf[0];
--}
--
--int ZEXPORT gzgetc_(file)
--gzFile file;
--{
--    return gzgetc(file);
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzungetc(c, file)
--    int c;
--    gzFile file;
--{
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--
--    /* check that we're reading and that there's no (serious) error */
--    if (state->mode != GZ_READ ||
--        (state->err != Z_OK && state->err != Z_BUF_ERROR))
--        return -1;
--
--    /* process a skip request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_skip(state, state->skip) == -1)
--            return -1;
--    }
--
--    /* can't push EOF */
--    if (c < 0)
--        return -1;
--
--    /* if output buffer empty, put byte at end (allows more pushing) */
--    if (state->x.have == 0) {
--        state->x.have = 1;
--        state->x.next = state->out + (state->size << 1) - 1;
--        state->x.next[0] = (unsigned char)c;
--        state->x.pos--;
--        state->past = 0;
--        return c;
--    }
--
--    /* if no room, give up (must have already done a gzungetc()) */
--    if (state->x.have == (state->size << 1)) {
--        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
--        return -1;
--    }
--
--    /* slide output data if needed and insert byte before existing data */
--    if (state->x.next == state->out) {
--        unsigned char *src = state->out + state->x.have;
--        unsigned char *dest = state->out + (state->size << 1);
--        while (src > state->out)
--            *--dest = *--src;
--        state->x.next = dest;
--    }
--    state->x.have++;
--    state->x.next--;
--    state->x.next[0] = (unsigned char)c;
--    state->x.pos--;
--    state->past = 0;
--    return c;
--}
--
--/* -- see zlib.h -- */
--char * ZEXPORT gzgets(file, buf, len)
--    gzFile file;
--    char *buf;
--    int len;
--{
--    unsigned left, n;
--    char *str;
--    unsigned char *eol;
--    gz_statep state;
--
--    /* check parameters and get internal structure */
--    if (file == NULL || buf == NULL || len < 1)
--        return NULL;
--    state = (gz_statep)file;
--
--    /* check that we're reading and that there's no (serious) error */
--    if (state->mode != GZ_READ ||
--        (state->err != Z_OK && state->err != Z_BUF_ERROR))
--        return NULL;
--
--    /* process a skip request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_skip(state, state->skip) == -1)
--            return NULL;
--    }
--
--    /* copy output bytes up to new line or len - 1, whichever comes first --
--       append a terminating zero to the string (we don't check for a zero in
--       the contents, let the user worry about that) */
--    str = buf;
--    left = (unsigned)len - 1;
--    if (left) do {
--        /* assure that something is in the output buffer */
--        if (state->x.have == 0 && gz_fetch(state) == -1)
--            return NULL;                /* error */
--        if (state->x.have == 0) {       /* end of file */
--            state->past = 1;            /* read past end */
--            break;                      /* return what we have */
--        }
--
--        /* look for end-of-line in current output buffer */
--        n = state->x.have > left ? left : state->x.have;
--        eol = (unsigned char *)memchr(state->x.next, '\n', n);
--        if (eol != NULL)
--            n = (unsigned)(eol - state->x.next) + 1;
--
--        /* copy through end-of-line, or remainder if not found */
--        memcpy(buf, state->x.next, n);
--        state->x.have -= n;
--        state->x.next += n;
--        state->x.pos += n;
--        left -= n;
--        buf += n;
--    } while (left && eol == NULL);
--
--    /* return terminated string, or if nothing, end of file */
--    if (buf == str)
--        return NULL;
--    buf[0] = 0;
--    return str;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzdirect(file)
--    gzFile file;
--{
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return 0;
--    state = (gz_statep)file;
--
--    /* if the state is not known, but we can find out, then do so (this is
--       mainly for right after a gzopen() or gzdopen()) */
--    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
--        (void)gz_look(state);
--
--    /* return 1 if transparent, 0 if processing a gzip stream */
--    return state->direct;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzclose_r(file)
--    gzFile file;
--{
--    int ret, err;
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--
--    /* check that we're reading */
--    if (state->mode != GZ_READ)
--        return Z_STREAM_ERROR;
--
--    /* free memory and close file */
--    if (state->size) {
--        inflateEnd(&(state->strm));
--        free(state->out);
--        free(state->in);
--    }
--    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;
--    gz_error(state, Z_OK, NULL);
--    free(state->path);
--    ret = close(state->fd);
--    free(state);
--    return ret ? Z_ERRNO : err;
--}
diff --cc zlib/gzwrite.c
index c7b5651d70b994e20222a734c620f68e11e0dc84,c7b5651d70b994e20222a734c620f68e11e0dc84..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,665 -1,665 +1,0 @@@
--/* gzwrite.c -- zlib functions for writing gzip files
-- * Copyright (C) 2004-2017 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#include "gzguts.h"
--
--/* Local functions */
--local int gz_init OF((gz_statep));
--local int gz_comp OF((gz_statep, int));
--local int gz_zero OF((gz_statep, z_off64_t));
--local z_size_t gz_write OF((gz_statep, voidpc, z_size_t));
--
--/* Initialize state for writing a gzip file.  Mark initialization by setting
--   state->size to non-zero.  Return -1 on a memory allocation failure, or 0 on
--   success. */
--local int gz_init(state)
--    gz_statep state;
--{
--    int ret;
--    z_streamp strm = &(state->strm);
--
--    /* allocate input buffer (double size for gzprintf) */
--    state->in = (unsigned char *)malloc(state->want << 1);
--    if (state->in == NULL) {
--        gz_error(state, Z_MEM_ERROR, "out of memory");
--        return -1;
--    }
--
--    /* only need output buffer and deflate state if compressing */
--    if (!state->direct) {
--        /* allocate output buffer */
--        state->out = (unsigned char *)malloc(state->want);
--        if (state->out == NULL) {
--            free(state->in);
--            gz_error(state, Z_MEM_ERROR, "out of memory");
--            return -1;
--        }
--
--        /* allocate deflate memory, set up for gzip compression */
--        strm->zalloc = Z_NULL;
--        strm->zfree = Z_NULL;
--        strm->opaque = Z_NULL;
--        ret = deflateInit2(strm, state->level, Z_DEFLATED,
--                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);
--        if (ret != Z_OK) {
--            free(state->out);
--            free(state->in);
--            gz_error(state, Z_MEM_ERROR, "out of memory");
--            return -1;
--        }
--        strm->next_in = NULL;
--    }
--
--    /* mark state as initialized */
--    state->size = state->want;
--
--    /* initialize write buffer if compressing */
--    if (!state->direct) {
--        strm->avail_out = state->size;
--        strm->next_out = state->out;
--        state->x.next = strm->next_out;
--    }
--    return 0;
--}
--
--/* Compress whatever is at avail_in and next_in and write to the output file.
--   Return -1 if there is an error writing to the output file or if gz_init()
--   fails to allocate memory, otherwise 0.  flush is assumed to be a valid
--   deflate() flush value.  If flush is Z_FINISH, then the deflate() state is
--   reset to start a new gzip stream.  If gz->direct is true, then simply write
--   to the output file without compressing, and ignore flush. */
--local int gz_comp(state, flush)
--    gz_statep state;
--    int flush;
--{
--    int ret, writ;
--    unsigned have, put, max = ((unsigned)-1 >> 2) + 1;
--    z_streamp strm = &(state->strm);
--
--    /* allocate memory if this is the first time through */
--    if (state->size == 0 && gz_init(state) == -1)
--        return -1;
--
--    /* write directly if requested */
--    if (state->direct) {
--        while (strm->avail_in) {
--            put = strm->avail_in > max ? max : strm->avail_in;
--            writ = write(state->fd, strm->next_in, put);
--            if (writ < 0) {
--                gz_error(state, Z_ERRNO, zstrerror());
--                return -1;
--            }
--            strm->avail_in -= (unsigned)writ;
--            strm->next_in += writ;
--        }
--        return 0;
--    }
--
--    /* run deflate() on provided input until it produces no more output */
--    ret = Z_OK;
--    do {
--        /* write out current buffer contents if full, or if flushing, but if
--           doing Z_FINISH then don't write until we get to Z_STREAM_END */
--        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
--            (flush != Z_FINISH || ret == Z_STREAM_END))) {
--            while (strm->next_out > state->x.next) {
--                put = strm->next_out - state->x.next > (int)max ? max :
--                      (unsigned)(strm->next_out - state->x.next);
--                writ = write(state->fd, state->x.next, put);
--                if (writ < 0) {
--                    gz_error(state, Z_ERRNO, zstrerror());
--                    return -1;
--                }
--                state->x.next += writ;
--            }
--            if (strm->avail_out == 0) {
--                strm->avail_out = state->size;
--                strm->next_out = state->out;
--                state->x.next = state->out;
--            }
--        }
--
--        /* compress */
--        have = strm->avail_out;
--        ret = deflate(strm, flush);
--        if (ret == Z_STREAM_ERROR) {
--            gz_error(state, Z_STREAM_ERROR,
--                      "internal error: deflate stream corrupt");
--            return -1;
--        }
--        have -= strm->avail_out;
--    } while (have);
--
--    /* if that completed a deflate stream, allow another to start */
--    if (flush == Z_FINISH)
--        deflateReset(strm);
--
--    /* all done, no errors */
--    return 0;
--}
--
--/* Compress len zeros to output.  Return -1 on a write error or memory
--   allocation failure by gz_comp(), or 0 on success. */
--local int gz_zero(state, len)
--    gz_statep state;
--    z_off64_t len;
--{
--    int first;
--    unsigned n;
--    z_streamp strm = &(state->strm);
--
--    /* consume whatever's left in the input buffer */
--    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
--        return -1;
--
--    /* compress len zeros (len guaranteed > 0) */
--    first = 1;
--    while (len) {
--        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
--            (unsigned)len : state->size;
--        if (first) {
--            memset(state->in, 0, n);
--            first = 0;
--        }
--        strm->avail_in = n;
--        strm->next_in = state->in;
--        state->x.pos += n;
--        if (gz_comp(state, Z_NO_FLUSH) == -1)
--            return -1;
--        len -= n;
--    }
--    return 0;
--}
--
--/* Write len bytes from buf to file.  Return the number of bytes written.  If
--   the returned value is less than len, then there was an error. */
--local z_size_t gz_write(state, buf, len)
--    gz_statep state;
--    voidpc buf;
--    z_size_t len;
--{
--    z_size_t put = len;
--
--    /* if len is zero, avoid unnecessary operations */
--    if (len == 0)
--        return 0;
--
--    /* allocate memory if this is the first time through */
--    if (state->size == 0 && gz_init(state) == -1)
--        return 0;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            return 0;
--    }
--
--    /* for small len, copy to input buffer, otherwise compress directly */
--    if (len < state->size) {
--        /* copy to input buffer, compress when full */
--        do {
--            unsigned have, copy;
--
--            if (state->strm.avail_in == 0)
--                state->strm.next_in = state->in;
--            have = (unsigned)((state->strm.next_in + state->strm.avail_in) -
--                              state->in);
--            copy = state->size - have;
--            if (copy > len)
--                copy = len;
--            memcpy(state->in + have, buf, copy);
--            state->strm.avail_in += copy;
--            state->x.pos += copy;
--            buf = (const char *)buf + copy;
--            len -= copy;
--            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
--                return 0;
--        } while (len);
--    }
--    else {
--        /* consume whatever's left in the input buffer */
--        if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
--            return 0;
--
--        /* directly compress user buffer to file */
--        state->strm.next_in = (z_const Bytef *)buf;
--        do {
--            unsigned n = (unsigned)-1;
--            if (n > len)
--                n = len;
--            state->strm.avail_in = n;
--            state->x.pos += n;
--            if (gz_comp(state, Z_NO_FLUSH) == -1)
--                return 0;
--            len -= n;
--        } while (len);
--    }
--
--    /* input was all buffered or compressed */
--    return put;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzwrite(file, buf, len)
--    gzFile file;
--    voidpc buf;
--    unsigned len;
--{
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return 0;
--    state = (gz_statep)file;
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return 0;
--
--    /* since an int is returned, make sure len fits in one, otherwise return
--       with an error (this avoids a flaw in the interface) */
--    if ((int)len < 0) {
--        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
--        return 0;
--    }
--
--    /* write len bytes from buf (the return value will fit in an int) */
--    return (int)gz_write(state, buf, len);
--}
--
--/* -- see zlib.h -- */
--z_size_t ZEXPORT gzfwrite(buf, size, nitems, file)
--    voidpc buf;
--    z_size_t size;
--    z_size_t nitems;
--    gzFile file;
--{
--    z_size_t len;
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return 0;
--    state = (gz_statep)file;
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return 0;
--
--    /* compute bytes to read -- error on overflow */
--    len = nitems * size;
--    if (size && len / size != nitems) {
--        gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");
--        return 0;
--    }
--
--    /* write len bytes to buf, return the number of full items written */
--    return len ? gz_write(state, buf, len) / size : 0;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzputc(file, c)
--    gzFile file;
--    int c;
--{
--    unsigned have;
--    unsigned char buf[1];
--    gz_statep state;
--    z_streamp strm;
--
--    /* get internal structure */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--    strm = &(state->strm);
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return -1;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            return -1;
--    }
--
--    /* try writing to input buffer for speed (state->size == 0 if buffer not
--       initialized) */
--    if (state->size) {
--        if (strm->avail_in == 0)
--            strm->next_in = state->in;
--        have = (unsigned)((strm->next_in + strm->avail_in) - state->in);
--        if (have < state->size) {
--            state->in[have] = (unsigned char)c;
--            strm->avail_in++;
--            state->x.pos++;
--            return c & 0xff;
--        }
--    }
--
--    /* no room in buffer or not initialized, use gz_write() */
--    buf[0] = (unsigned char)c;
--    if (gz_write(state, buf, 1) != 1)
--        return -1;
--    return c & 0xff;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzputs(file, str)
--    gzFile file;
--    const char *str;
--{
--    int ret;
--    z_size_t len;
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return -1;
--    state = (gz_statep)file;
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return -1;
--
--    /* write string */
--    len = strlen(str);
--    ret = gz_write(state, str, len);
--    return ret == 0 && len != 0 ? -1 : ret;
--}
--
--#if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#include <stdarg.h>
--
--/* -- see zlib.h -- */
--int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)
--{
--    int len;
--    unsigned left;
--    char *next;
--    gz_statep state;
--    z_streamp strm;
--
--    /* get internal structure */
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--    strm = &(state->strm);
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return Z_STREAM_ERROR;
--
--    /* make sure we have some buffer space */
--    if (state->size == 0 && gz_init(state) == -1)
--        return state->err;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            return state->err;
--    }
--
--    /* do the printf() into the input buffer, put length in len -- the input
--       buffer is double-sized just for this function, so there is guaranteed to
--       be state->size bytes available after the current contents */
--    if (strm->avail_in == 0)
--        strm->next_in = state->in;
--    next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in);
--    next[state->size - 1] = 0;
--#ifdef NO_vsnprintf
--#  ifdef HAS_vsprintf_void
--    (void)vsprintf(next, format, va);
--    for (len = 0; len < state->size; len++)
--        if (next[len] == 0) break;
--#  else
--    len = vsprintf(next, format, va);
--#  endif
--#else
--#  ifdef HAS_vsnprintf_void
--    (void)vsnprintf(next, state->size, format, va);
--    len = strlen(next);
--#  else
--    len = vsnprintf(next, state->size, format, va);
--#  endif
--#endif
--
--    /* check that printf() results fit in buffer */
--    if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0)
--        return 0;
--
--    /* update buffer and position, compress first half if past that */
--    strm->avail_in += (unsigned)len;
--    state->x.pos += len;
--    if (strm->avail_in >= state->size) {
--        left = strm->avail_in - state->size;
--        strm->avail_in = state->size;
--        if (gz_comp(state, Z_NO_FLUSH) == -1)
--            return state->err;
--        memcpy(state->in, state->in + state->size, left);
--        strm->next_in = state->in;
--        strm->avail_in = left;
--    }
--    return len;
--}
--
--int ZEXPORTVA gzprintf(gzFile file, const char *format, ...)
--{
--    va_list va;
--    int ret;
--
--    va_start(va, format);
--    ret = gzvprintf(file, format, va);
--    va_end(va);
--    return ret;
--}
--
--#else /* !STDC && !Z_HAVE_STDARG_H */
--
--/* -- see zlib.h -- */
--int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
--                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
--    gzFile file;
--    const char *format;
--    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
--        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
--{
--    unsigned len, left;
--    char *next;
--    gz_statep state;
--    z_streamp strm;
--
--    /* get internal structure */
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--    strm = &(state->strm);
--
--    /* check that can really pass pointer in ints */
--    if (sizeof(int) != sizeof(void *))
--        return Z_STREAM_ERROR;
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return Z_STREAM_ERROR;
--
--    /* make sure we have some buffer space */
--    if (state->size == 0 && gz_init(state) == -1)
--        return state->error;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            return state->error;
--    }
--
--    /* do the printf() into the input buffer, put length in len -- the input
--       buffer is double-sized just for this function, so there is guaranteed to
--       be state->size bytes available after the current contents */
--    if (strm->avail_in == 0)
--        strm->next_in = state->in;
--    next = (char *)(strm->next_in + strm->avail_in);
--    next[state->size - 1] = 0;
--#ifdef NO_snprintf
--#  ifdef HAS_sprintf_void
--    sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12,
--            a13, a14, a15, a16, a17, a18, a19, a20);
--    for (len = 0; len < size; len++)
--        if (next[len] == 0)
--            break;
--#  else
--    len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11,
--                  a12, a13, a14, a15, a16, a17, a18, a19, a20);
--#  endif
--#else
--#  ifdef HAS_snprintf_void
--    snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9,
--             a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
--    len = strlen(next);
--#  else
--    len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8,
--                   a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
--#  endif
--#endif
--
--    /* check that printf() results fit in buffer */
--    if (len == 0 || len >= state->size || next[state->size - 1] != 0)
--        return 0;
--
--    /* update buffer and position, compress first half if past that */
--    strm->avail_in += len;
--    state->x.pos += len;
--    if (strm->avail_in >= state->size) {
--        left = strm->avail_in - state->size;
--        strm->avail_in = state->size;
--        if (gz_comp(state, Z_NO_FLUSH) == -1)
--            return state->err;
--        memcpy(state->in, state->in + state->size, left);
--        strm->next_in = state->in;
--        strm->avail_in = left;
--    }
--    return (int)len;
--}
--
--#endif
--
--/* -- see zlib.h -- */
--int ZEXPORT gzflush(file, flush)
--    gzFile file;
--    int flush;
--{
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return Z_STREAM_ERROR;
--
--    /* check flush parameter */
--    if (flush < 0 || flush > Z_FINISH)
--        return Z_STREAM_ERROR;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            return state->err;
--    }
--
--    /* compress remaining data with requested flush */
--    (void)gz_comp(state, flush);
--    return state->err;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzsetparams(file, level, strategy)
--    gzFile file;
--    int level;
--    int strategy;
--{
--    gz_statep state;
--    z_streamp strm;
--
--    /* get internal structure */
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--    strm = &(state->strm);
--
--    /* check that we're writing and that there's no error */
--    if (state->mode != GZ_WRITE || state->err != Z_OK)
--        return Z_STREAM_ERROR;
--
--    /* if no change is requested, then do nothing */
--    if (level == state->level && strategy == state->strategy)
--        return Z_OK;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            return state->err;
--    }
--
--    /* change compression parameters for subsequent input */
--    if (state->size) {
--        /* flush previous input with previous parameters before changing */
--        if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1)
--            return state->err;
--        deflateParams(strm, level, strategy);
--    }
--    state->level = level;
--    state->strategy = strategy;
--    return Z_OK;
--}
--
--/* -- see zlib.h -- */
--int ZEXPORT gzclose_w(file)
--    gzFile file;
--{
--    int ret = Z_OK;
--    gz_statep state;
--
--    /* get internal structure */
--    if (file == NULL)
--        return Z_STREAM_ERROR;
--    state = (gz_statep)file;
--
--    /* check that we're writing */
--    if (state->mode != GZ_WRITE)
--        return Z_STREAM_ERROR;
--
--    /* check for seek request */
--    if (state->seek) {
--        state->seek = 0;
--        if (gz_zero(state, state->skip) == -1)
--            ret = state->err;
--    }
--
--    /* flush, free memory, and close file */
--    if (gz_comp(state, Z_FINISH) == -1)
--        ret = state->err;
--    if (state->size) {
--        if (!state->direct) {
--            (void)deflateEnd(&(state->strm));
--            free(state->out);
--        }
--        free(state->in);
--    }
--    gz_error(state, Z_OK, NULL);
--    free(state->path);
--    if (close(state->fd) == -1)
--        ret = Z_ERRNO;
--    free(state);
--    return ret;
--}
diff --cc zlib/infback.c
index 59679ecbfc5d778ca85d9ced87565f69bcb4635c,59679ecbfc5d778ca85d9ced87565f69bcb4635c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,640 -1,640 +1,0 @@@
--/* infback.c -- inflate using a call-back interface
-- * Copyright (C) 1995-2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/*
--   This code is largely copied from inflate.c.  Normally either infback.o or
--   inflate.o would be linked into an application--not both.  The interface
--   with inffast.c is retained so that optimized assembler-coded versions of
--   inflate_fast() can be used with either inflate.c or infback.c.
-- */
--
--#include "zutil.h"
--#include "inftrees.h"
--#include "inflate.h"
--#include "inffast.h"
--
--/* function prototypes */
--local void fixedtables OF((struct inflate_state FAR *state));
--
--/*
--   strm provides memory allocation functions in zalloc and zfree, or
--   Z_NULL to use the library memory allocation functions.
--
--   windowBits is in the range 8..15, and window is a user-supplied
--   window and output buffer that is 2**windowBits bytes.
-- */
--int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
--z_streamp strm;
--int windowBits;
--unsigned char FAR *window;
--const char *version;
--int stream_size;
--{
--    struct inflate_state FAR *state;
--
--    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
--        stream_size != (int)(sizeof(z_stream)))
--        return Z_VERSION_ERROR;
--    if (strm == Z_NULL || window == Z_NULL ||
--        windowBits < 8 || windowBits > 15)
--        return Z_STREAM_ERROR;
--    strm->msg = Z_NULL;                 /* in case we return an error */
--    if (strm->zalloc == (alloc_func)0) {
--#ifdef Z_SOLO
--        return Z_STREAM_ERROR;
--#else
--        strm->zalloc = zcalloc;
--        strm->opaque = (voidpf)0;
--#endif
--    }
--    if (strm->zfree == (free_func)0)
--#ifdef Z_SOLO
--        return Z_STREAM_ERROR;
--#else
--    strm->zfree = zcfree;
--#endif
--    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
--                                               sizeof(struct inflate_state));
--    if (state == Z_NULL) return Z_MEM_ERROR;
--    Tracev((stderr, "inflate: allocated\n"));
--    strm->state = (struct internal_state FAR *)state;
--    state->dmax = 32768U;
--    state->wbits = (uInt)windowBits;
--    state->wsize = 1U << windowBits;
--    state->window = window;
--    state->wnext = 0;
--    state->whave = 0;
--    return Z_OK;
--}
--
--/*
--   Return state with length and distance decoding tables and index sizes set to
--   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
--   If BUILDFIXED is defined, then instead this routine builds the tables the
--   first time it's called, and returns those tables the first time and
--   thereafter.  This reduces the size of the code by about 2K bytes, in
--   exchange for a little execution time.  However, BUILDFIXED should not be
--   used for threaded applications, since the rewriting of the tables and virgin
--   may not be thread-safe.
-- */
--local void fixedtables(state)
--struct inflate_state FAR *state;
--{
--#ifdef BUILDFIXED
--    static int virgin = 1;
--    static code *lenfix, *distfix;
--    static code fixed[544];
--
--    /* build fixed huffman tables if first call (may not be thread safe) */
--    if (virgin) {
--        unsigned sym, bits;
--        static code *next;
--
--        /* literal/length table */
--        sym = 0;
--        while (sym < 144) state->lens[sym++] = 8;
--        while (sym < 256) state->lens[sym++] = 9;
--        while (sym < 280) state->lens[sym++] = 7;
--        while (sym < 288) state->lens[sym++] = 8;
--        next = fixed;
--        lenfix = next;
--        bits = 9;
--        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
--
--        /* distance table */
--        sym = 0;
--        while (sym < 32) state->lens[sym++] = 5;
--        distfix = next;
--        bits = 5;
--        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
--
--        /* do this just once */
--        virgin = 0;
--    }
--#else /* !BUILDFIXED */
--#   include "inffixed.h"
--#endif /* BUILDFIXED */
--    state->lencode = lenfix;
--    state->lenbits = 9;
--    state->distcode = distfix;
--    state->distbits = 5;
--}
--
--/* Macros for inflateBack(): */
--
--/* Load returned state from inflate_fast() */
--#define LOAD() \
--    do { \
--        put = strm->next_out; \
--        left = strm->avail_out; \
--        next = strm->next_in; \
--        have = strm->avail_in; \
--        hold = state->hold; \
--        bits = state->bits; \
--    } while (0)
--
--/* Set state from registers for inflate_fast() */
--#define RESTORE() \
--    do { \
--        strm->next_out = put; \
--        strm->avail_out = left; \
--        strm->next_in = next; \
--        strm->avail_in = have; \
--        state->hold = hold; \
--        state->bits = bits; \
--    } while (0)
--
--/* Clear the input bit accumulator */
--#define INITBITS() \
--    do { \
--        hold = 0; \
--        bits = 0; \
--    } while (0)
--
--/* Assure that some input is available.  If input is requested, but denied,
--   then return a Z_BUF_ERROR from inflateBack(). */
--#define PULL() \
--    do { \
--        if (have == 0) { \
--            have = in(in_desc, &next); \
--            if (have == 0) { \
--                next = Z_NULL; \
--                ret = Z_BUF_ERROR; \
--                goto inf_leave; \
--            } \
--        } \
--    } while (0)
--
--/* Get a byte of input into the bit accumulator, or return from inflateBack()
--   with an error if there is no input available. */
--#define PULLBYTE() \
--    do { \
--        PULL(); \
--        have--; \
--        hold += (unsigned long)(*next++) << bits; \
--        bits += 8; \
--    } while (0)
--
--/* Assure that there are at least n bits in the bit accumulator.  If there is
--   not enough available input to do that, then return from inflateBack() with
--   an error. */
--#define NEEDBITS(n) \
--    do { \
--        while (bits < (unsigned)(n)) \
--            PULLBYTE(); \
--    } while (0)
--
--/* Return the low n bits of the bit accumulator (n < 16) */
--#define BITS(n) \
--    ((unsigned)hold & ((1U << (n)) - 1))
--
--/* Remove n bits from the bit accumulator */
--#define DROPBITS(n) \
--    do { \
--        hold >>= (n); \
--        bits -= (unsigned)(n); \
--    } while (0)
--
--/* Remove zero to seven bits as needed to go to a byte boundary */
--#define BYTEBITS() \
--    do { \
--        hold >>= bits & 7; \
--        bits -= bits & 7; \
--    } while (0)
--
--/* Assure that some output space is available, by writing out the window
--   if it's full.  If the write fails, return from inflateBack() with a
--   Z_BUF_ERROR. */
--#define ROOM() \
--    do { \
--        if (left == 0) { \
--            put = state->window; \
--            left = state->wsize; \
--            state->whave = left; \
--            if (out(out_desc, put, left)) { \
--                ret = Z_BUF_ERROR; \
--                goto inf_leave; \
--            } \
--        } \
--    } while (0)
--
--/*
--   strm provides the memory allocation functions and window buffer on input,
--   and provides information on the unused input on return.  For Z_DATA_ERROR
--   returns, strm will also provide an error message.
--
--   in() and out() are the call-back input and output functions.  When
--   inflateBack() needs more input, it calls in().  When inflateBack() has
--   filled the window with output, or when it completes with data in the
--   window, it calls out() to write out the data.  The application must not
--   change the provided input until in() is called again or inflateBack()
--   returns.  The application must not change the window/output buffer until
--   inflateBack() returns.
--
--   in() and out() are called with a descriptor parameter provided in the
--   inflateBack() call.  This parameter can be a structure that provides the
--   information required to do the read or write, as well as accumulated
--   information on the input and output such as totals and check values.
--
--   in() should return zero on failure.  out() should return non-zero on
--   failure.  If either in() or out() fails, than inflateBack() returns a
--   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
--   was in() or out() that caused in the error.  Otherwise,  inflateBack()
--   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
--   error, or Z_MEM_ERROR if it could not allocate memory for the state.
--   inflateBack() can also return Z_STREAM_ERROR if the input parameters
--   are not correct, i.e. strm is Z_NULL or the state was not initialized.
-- */
--int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
--z_streamp strm;
--in_func in;
--void FAR *in_desc;
--out_func out;
--void FAR *out_desc;
--{
--    struct inflate_state FAR *state;
--    z_const unsigned char FAR *next;    /* next input */
--    unsigned char FAR *put;     /* next output */
--    unsigned have, left;        /* available input and output */
--    unsigned long hold;         /* bit buffer */
--    unsigned bits;              /* bits in bit buffer */
--    unsigned copy;              /* number of stored or match bytes to copy */
--    unsigned char FAR *from;    /* where to copy match bytes from */
--    code here;                  /* current decoding table entry */
--    code last;                  /* parent table entry */
--    unsigned len;               /* length to copy for repeats, bits to drop */
--    int ret;                    /* return code */
--    static const unsigned short order[19] = /* permutation of code lengths */
--        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
--
--    /* Check that the strm exists and that the state was initialized */
--    if (strm == Z_NULL || strm->state == Z_NULL)
--        return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--
--    /* Reset the state */
--    strm->msg = Z_NULL;
--    state->mode = TYPE;
--    state->last = 0;
--    state->whave = 0;
--    next = strm->next_in;
--    have = next != Z_NULL ? strm->avail_in : 0;
--    hold = 0;
--    bits = 0;
--    put = state->window;
--    left = state->wsize;
--
--    /* Inflate until end of block marked as last */
--    for (;;)
--        switch (state->mode) {
--        case TYPE:
--            /* determine and dispatch block type */
--            if (state->last) {
--                BYTEBITS();
--                state->mode = DONE;
--                break;
--            }
--            NEEDBITS(3);
--            state->last = BITS(1);
--            DROPBITS(1);
--            switch (BITS(2)) {
--            case 0:                             /* stored block */
--                Tracev((stderr, "inflate:     stored block%s\n",
--                        state->last ? " (last)" : ""));
--                state->mode = STORED;
--                break;
--            case 1:                             /* fixed block */
--                fixedtables(state);
--                Tracev((stderr, "inflate:     fixed codes block%s\n",
--                        state->last ? " (last)" : ""));
--                state->mode = LEN;              /* decode codes */
--                break;
--            case 2:                             /* dynamic block */
--                Tracev((stderr, "inflate:     dynamic codes block%s\n",
--                        state->last ? " (last)" : ""));
--                state->mode = TABLE;
--                break;
--            case 3:
--                strm->msg = (char *)"invalid block type";
--                state->mode = BAD;
--            }
--            DROPBITS(2);
--            break;
--
--        case STORED:
--            /* get and verify stored block length */
--            BYTEBITS();                         /* go to byte boundary */
--            NEEDBITS(32);
--            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
--                strm->msg = (char *)"invalid stored block lengths";
--                state->mode = BAD;
--                break;
--            }
--            state->length = (unsigned)hold & 0xffff;
--            Tracev((stderr, "inflate:       stored length %u\n",
--                    state->length));
--            INITBITS();
--
--            /* copy stored block from input to output */
--            while (state->length != 0) {
--                copy = state->length;
--                PULL();
--                ROOM();
--                if (copy > have) copy = have;
--                if (copy > left) copy = left;
--                zmemcpy(put, next, copy);
--                have -= copy;
--                next += copy;
--                left -= copy;
--                put += copy;
--                state->length -= copy;
--            }
--            Tracev((stderr, "inflate:       stored end\n"));
--            state->mode = TYPE;
--            break;
--
--        case TABLE:
--            /* get dynamic table entries descriptor */
--            NEEDBITS(14);
--            state->nlen = BITS(5) + 257;
--            DROPBITS(5);
--            state->ndist = BITS(5) + 1;
--            DROPBITS(5);
--            state->ncode = BITS(4) + 4;
--            DROPBITS(4);
--#ifndef PKZIP_BUG_WORKAROUND
--            if (state->nlen > 286 || state->ndist > 30) {
--                strm->msg = (char *)"too many length or distance symbols";
--                state->mode = BAD;
--                break;
--            }
--#endif
--            Tracev((stderr, "inflate:       table sizes ok\n"));
--
--            /* get code length code lengths (not a typo) */
--            state->have = 0;
--            while (state->have < state->ncode) {
--                NEEDBITS(3);
--                state->lens[order[state->have++]] = (unsigned short)BITS(3);
--                DROPBITS(3);
--            }
--            while (state->have < 19)
--                state->lens[order[state->have++]] = 0;
--            state->next = state->codes;
--            state->lencode = (code const FAR *)(state->next);
--            state->lenbits = 7;
--            ret = inflate_table(CODES, state->lens, 19, &(state->next),
--                                &(state->lenbits), state->work);
--            if (ret) {
--                strm->msg = (char *)"invalid code lengths set";
--                state->mode = BAD;
--                break;
--            }
--            Tracev((stderr, "inflate:       code lengths ok\n"));
--
--            /* get length and distance code code lengths */
--            state->have = 0;
--            while (state->have < state->nlen + state->ndist) {
--                for (;;) {
--                    here = state->lencode[BITS(state->lenbits)];
--                    if ((unsigned)(here.bits) <= bits) break;
--                    PULLBYTE();
--                }
--                if (here.val < 16) {
--                    DROPBITS(here.bits);
--                    state->lens[state->have++] = here.val;
--                }
--                else {
--                    if (here.val == 16) {
--                        NEEDBITS(here.bits + 2);
--                        DROPBITS(here.bits);
--                        if (state->have == 0) {
--                            strm->msg = (char *)"invalid bit length repeat";
--                            state->mode = BAD;
--                            break;
--                        }
--                        len = (unsigned)(state->lens[state->have - 1]);
--                        copy = 3 + BITS(2);
--                        DROPBITS(2);
--                    }
--                    else if (here.val == 17) {
--                        NEEDBITS(here.bits + 3);
--                        DROPBITS(here.bits);
--                        len = 0;
--                        copy = 3 + BITS(3);
--                        DROPBITS(3);
--                    }
--                    else {
--                        NEEDBITS(here.bits + 7);
--                        DROPBITS(here.bits);
--                        len = 0;
--                        copy = 11 + BITS(7);
--                        DROPBITS(7);
--                    }
--                    if (state->have + copy > state->nlen + state->ndist) {
--                        strm->msg = (char *)"invalid bit length repeat";
--                        state->mode = BAD;
--                        break;
--                    }
--                    while (copy--)
--                        state->lens[state->have++] = (unsigned short)len;
--                }
--            }
--
--            /* handle error breaks in while */
--            if (state->mode == BAD) break;
--
--            /* check for end-of-block code (better have one) */
--            if (state->lens[256] == 0) {
--                strm->msg = (char *)"invalid code -- missing end-of-block";
--                state->mode = BAD;
--                break;
--            }
--
--            /* build code tables -- note: do not change the lenbits or distbits
--               values here (9 and 6) without reading the comments in inftrees.h
--               concerning the ENOUGH constants, which depend on those values */
--            state->next = state->codes;
--            state->lencode = (code const FAR *)(state->next);
--            state->lenbits = 9;
--            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
--                                &(state->lenbits), state->work);
--            if (ret) {
--                strm->msg = (char *)"invalid literal/lengths set";
--                state->mode = BAD;
--                break;
--            }
--            state->distcode = (code const FAR *)(state->next);
--            state->distbits = 6;
--            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
--                            &(state->next), &(state->distbits), state->work);
--            if (ret) {
--                strm->msg = (char *)"invalid distances set";
--                state->mode = BAD;
--                break;
--            }
--            Tracev((stderr, "inflate:       codes ok\n"));
--            state->mode = LEN;
--
--        case LEN:
--            /* use inflate_fast() if we have enough input and output */
--            if (have >= 6 && left >= 258) {
--                RESTORE();
--                if (state->whave < state->wsize)
--                    state->whave = state->wsize - left;
--                inflate_fast(strm, state->wsize);
--                LOAD();
--                break;
--            }
--
--            /* get a literal, length, or end-of-block code */
--            for (;;) {
--                here = state->lencode[BITS(state->lenbits)];
--                if ((unsigned)(here.bits) <= bits) break;
--                PULLBYTE();
--            }
--            if (here.op && (here.op & 0xf0) == 0) {
--                last = here;
--                for (;;) {
--                    here = state->lencode[last.val +
--                            (BITS(last.bits + last.op) >> last.bits)];
--                    if ((unsigned)(last.bits + here.bits) <= bits) break;
--                    PULLBYTE();
--                }
--                DROPBITS(last.bits);
--            }
--            DROPBITS(here.bits);
--            state->length = (unsigned)here.val;
--
--            /* process literal */
--            if (here.op == 0) {
--                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
--                        "inflate:         literal '%c'\n" :
--                        "inflate:         literal 0x%02x\n", here.val));
--                ROOM();
--                *put++ = (unsigned char)(state->length);
--                left--;
--                state->mode = LEN;
--                break;
--            }
--
--            /* process end of block */
--            if (here.op & 32) {
--                Tracevv((stderr, "inflate:         end of block\n"));
--                state->mode = TYPE;
--                break;
--            }
--
--            /* invalid code */
--            if (here.op & 64) {
--                strm->msg = (char *)"invalid literal/length code";
--                state->mode = BAD;
--                break;
--            }
--
--            /* length code -- get extra bits, if any */
--            state->extra = (unsigned)(here.op) & 15;
--            if (state->extra != 0) {
--                NEEDBITS(state->extra);
--                state->length += BITS(state->extra);
--                DROPBITS(state->extra);
--            }
--            Tracevv((stderr, "inflate:         length %u\n", state->length));
--
--            /* get distance code */
--            for (;;) {
--                here = state->distcode[BITS(state->distbits)];
--                if ((unsigned)(here.bits) <= bits) break;
--                PULLBYTE();
--            }
--            if ((here.op & 0xf0) == 0) {
--                last = here;
--                for (;;) {
--                    here = state->distcode[last.val +
--                            (BITS(last.bits + last.op) >> last.bits)];
--                    if ((unsigned)(last.bits + here.bits) <= bits) break;
--                    PULLBYTE();
--                }
--                DROPBITS(last.bits);
--            }
--            DROPBITS(here.bits);
--            if (here.op & 64) {
--                strm->msg = (char *)"invalid distance code";
--                state->mode = BAD;
--                break;
--            }
--            state->offset = (unsigned)here.val;
--
--            /* get distance extra bits, if any */
--            state->extra = (unsigned)(here.op) & 15;
--            if (state->extra != 0) {
--                NEEDBITS(state->extra);
--                state->offset += BITS(state->extra);
--                DROPBITS(state->extra);
--            }
--            if (state->offset > state->wsize - (state->whave < state->wsize ?
--                                                left : 0)) {
--                strm->msg = (char *)"invalid distance too far back";
--                state->mode = BAD;
--                break;
--            }
--            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
--
--            /* copy match from window to output */
--            do {
--                ROOM();
--                copy = state->wsize - state->offset;
--                if (copy < left) {
--                    from = put + copy;
--                    copy = left - copy;
--                }
--                else {
--                    from = put - state->offset;
--                    copy = left;
--                }
--                if (copy > state->length) copy = state->length;
--                state->length -= copy;
--                left -= copy;
--                do {
--                    *put++ = *from++;
--                } while (--copy);
--            } while (state->length != 0);
--            break;
--
--        case DONE:
--            /* inflate stream terminated properly -- write leftover output */
--            ret = Z_STREAM_END;
--            if (left < state->wsize) {
--                if (out(out_desc, state->window, state->wsize - left))
--                    ret = Z_BUF_ERROR;
--            }
--            goto inf_leave;
--
--        case BAD:
--            ret = Z_DATA_ERROR;
--            goto inf_leave;
--
--        default:                /* can't happen, but makes compilers happy */
--            ret = Z_STREAM_ERROR;
--            goto inf_leave;
--        }
--
--    /* Return unused input */
--  inf_leave:
--    strm->next_in = next;
--    strm->avail_in = have;
--    return ret;
--}
--
--int ZEXPORT inflateBackEnd(strm)
--z_streamp strm;
--{
--    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
--        return Z_STREAM_ERROR;
--    ZFREE(strm, strm->state);
--    strm->state = Z_NULL;
--    Tracev((stderr, "inflate: end\n"));
--    return Z_OK;
--}
diff --cc zlib/inffast.c
index 0dbd1dbc09f2f69425405863bfe1080e3ca2b3f5,0dbd1dbc09f2f69425405863bfe1080e3ca2b3f5..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,323 -1,323 +1,0 @@@
--/* inffast.c -- fast decoding
-- * Copyright (C) 1995-2017 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#include "zutil.h"
--#include "inftrees.h"
--#include "inflate.h"
--#include "inffast.h"
--
--#ifdef ASMINF
--#  pragma message("Assembler code may have bugs -- use at your own risk")
--#else
--
--/*
--   Decode literal, length, and distance codes and write out the resulting
--   literal and match bytes until either not enough input or output is
--   available, an end-of-block is encountered, or a data error is encountered.
--   When large enough input and output buffers are supplied to inflate(), for
--   example, a 16K input buffer and a 64K output buffer, more than 95% of the
--   inflate execution time is spent in this routine.
--
--   Entry assumptions:
--
--        state->mode == LEN
--        strm->avail_in >= 6
--        strm->avail_out >= 258
--        start >= strm->avail_out
--        state->bits < 8
--
--   On return, state->mode is one of:
--
--        LEN -- ran out of enough output space or enough available input
--        TYPE -- reached end of block code, inflate() to interpret next block
--        BAD -- error in block data
--
--   Notes:
--
--    - The maximum input bits used by a length/distance pair is 15 bits for the
--      length code, 5 bits for the length extra, 15 bits for the distance code,
--      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
--      Therefore if strm->avail_in >= 6, then there is enough input to avoid
--      checking for available input while decoding.
--
--    - The maximum bytes that a single length/distance pair can output is 258
--      bytes, which is the maximum length that can be coded.  inflate_fast()
--      requires strm->avail_out >= 258 for each loop to avoid checking for
--      output space.
-- */
--void ZLIB_INTERNAL inflate_fast(strm, start)
--z_streamp strm;
--unsigned start;         /* inflate()'s starting value for strm->avail_out */
--{
--    struct inflate_state FAR *state;
--    z_const unsigned char FAR *in;      /* local strm->next_in */
--    z_const unsigned char FAR *last;    /* have enough input while in < last */
--    unsigned char FAR *out;     /* local strm->next_out */
--    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
--    unsigned char FAR *end;     /* while out < end, enough space available */
--#ifdef INFLATE_STRICT
--    unsigned dmax;              /* maximum distance from zlib header */
--#endif
--    unsigned wsize;             /* window size or zero if not using window */
--    unsigned whave;             /* valid bytes in the window */
--    unsigned wnext;             /* window write index */
--    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
--    unsigned long hold;         /* local strm->hold */
--    unsigned bits;              /* local strm->bits */
--    code const FAR *lcode;      /* local strm->lencode */
--    code const FAR *dcode;      /* local strm->distcode */
--    unsigned lmask;             /* mask for first level of length codes */
--    unsigned dmask;             /* mask for first level of distance codes */
--    code here;                  /* retrieved table entry */
--    unsigned op;                /* code bits, operation, extra bits, or */
--                                /*  window position, window bytes to copy */
--    unsigned len;               /* match length, unused bytes */
--    unsigned dist;              /* match distance */
--    unsigned char FAR *from;    /* where to copy match from */
--
--    /* copy state to local variables */
--    state = (struct inflate_state FAR *)strm->state;
--    in = strm->next_in;
--    last = in + (strm->avail_in - 5);
--    out = strm->next_out;
--    beg = out - (start - strm->avail_out);
--    end = out + (strm->avail_out - 257);
--#ifdef INFLATE_STRICT
--    dmax = state->dmax;
--#endif
--    wsize = state->wsize;
--    whave = state->whave;
--    wnext = state->wnext;
--    window = state->window;
--    hold = state->hold;
--    bits = state->bits;
--    lcode = state->lencode;
--    dcode = state->distcode;
--    lmask = (1U << state->lenbits) - 1;
--    dmask = (1U << state->distbits) - 1;
--
--    /* decode literals and length/distances until end-of-block or not enough
--       input data or output space */
--    do {
--        if (bits < 15) {
--            hold += (unsigned long)(*in++) << bits;
--            bits += 8;
--            hold += (unsigned long)(*in++) << bits;
--            bits += 8;
--        }
--        here = lcode[hold & lmask];
--      dolen:
--        op = (unsigned)(here.bits);
--        hold >>= op;
--        bits -= op;
--        op = (unsigned)(here.op);
--        if (op == 0) {                          /* literal */
--            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
--                    "inflate:         literal '%c'\n" :
--                    "inflate:         literal 0x%02x\n", here.val));
--            *out++ = (unsigned char)(here.val);
--        }
--        else if (op & 16) {                     /* length base */
--            len = (unsigned)(here.val);
--            op &= 15;                           /* number of extra bits */
--            if (op) {
--                if (bits < op) {
--                    hold += (unsigned long)(*in++) << bits;
--                    bits += 8;
--                }
--                len += (unsigned)hold & ((1U << op) - 1);
--                hold >>= op;
--                bits -= op;
--            }
--            Tracevv((stderr, "inflate:         length %u\n", len));
--            if (bits < 15) {
--                hold += (unsigned long)(*in++) << bits;
--                bits += 8;
--                hold += (unsigned long)(*in++) << bits;
--                bits += 8;
--            }
--            here = dcode[hold & dmask];
--          dodist:
--            op = (unsigned)(here.bits);
--            hold >>= op;
--            bits -= op;
--            op = (unsigned)(here.op);
--            if (op & 16) {                      /* distance base */
--                dist = (unsigned)(here.val);
--                op &= 15;                       /* number of extra bits */
--                if (bits < op) {
--                    hold += (unsigned long)(*in++) << bits;
--                    bits += 8;
--                    if (bits < op) {
--                        hold += (unsigned long)(*in++) << bits;
--                        bits += 8;
--                    }
--                }
--                dist += (unsigned)hold & ((1U << op) - 1);
--#ifdef INFLATE_STRICT
--                if (dist > dmax) {
--                    strm->msg = (char *)"invalid distance too far back";
--                    state->mode = BAD;
--                    break;
--                }
--#endif
--                hold >>= op;
--                bits -= op;
--                Tracevv((stderr, "inflate:         distance %u\n", dist));
--                op = (unsigned)(out - beg);     /* max distance in output */
--                if (dist > op) {                /* see if copy from window */
--                    op = dist - op;             /* distance back in window */
--                    if (op > whave) {
--                        if (state->sane) {
--                            strm->msg =
--                                (char *)"invalid distance too far back";
--                            state->mode = BAD;
--                            break;
--                        }
--#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
--                        if (len <= op - whave) {
--                            do {
--                                *out++ = 0;
--                            } while (--len);
--                            continue;
--                        }
--                        len -= op - whave;
--                        do {
--                            *out++ = 0;
--                        } while (--op > whave);
--                        if (op == 0) {
--                            from = out - dist;
--                            do {
--                                *out++ = *from++;
--                            } while (--len);
--                            continue;
--                        }
--#endif
--                    }
--                    from = window;
--                    if (wnext == 0) {           /* very common case */
--                        from += wsize - op;
--                        if (op < len) {         /* some from window */
--                            len -= op;
--                            do {
--                                *out++ = *from++;
--                            } while (--op);
--                            from = out - dist;  /* rest from output */
--                        }
--                    }
--                    else if (wnext < op) {      /* wrap around window */
--                        from += wsize + wnext - op;
--                        op -= wnext;
--                        if (op < len) {         /* some from end of window */
--                            len -= op;
--                            do {
--                                *out++ = *from++;
--                            } while (--op);
--                            from = window;
--                            if (wnext < len) {  /* some from start of window */
--                                op = wnext;
--                                len -= op;
--                                do {
--                                    *out++ = *from++;
--                                } while (--op);
--                                from = out - dist;      /* rest from output */
--                            }
--                        }
--                    }
--                    else {                      /* contiguous in window */
--                        from += wnext - op;
--                        if (op < len) {         /* some from window */
--                            len -= op;
--                            do {
--                                *out++ = *from++;
--                            } while (--op);
--                            from = out - dist;  /* rest from output */
--                        }
--                    }
--                    while (len > 2) {
--                        *out++ = *from++;
--                        *out++ = *from++;
--                        *out++ = *from++;
--                        len -= 3;
--                    }
--                    if (len) {
--                        *out++ = *from++;
--                        if (len > 1)
--                            *out++ = *from++;
--                    }
--                }
--                else {
--                    from = out - dist;          /* copy direct from output */
--                    do {                        /* minimum length is three */
--                        *out++ = *from++;
--                        *out++ = *from++;
--                        *out++ = *from++;
--                        len -= 3;
--                    } while (len > 2);
--                    if (len) {
--                        *out++ = *from++;
--                        if (len > 1)
--                            *out++ = *from++;
--                    }
--                }
--            }
--            else if ((op & 64) == 0) {          /* 2nd level distance code */
--                here = dcode[here.val + (hold & ((1U << op) - 1))];
--                goto dodist;
--            }
--            else {
--                strm->msg = (char *)"invalid distance code";
--                state->mode = BAD;
--                break;
--            }
--        }
--        else if ((op & 64) == 0) {              /* 2nd level length code */
--            here = lcode[here.val + (hold & ((1U << op) - 1))];
--            goto dolen;
--        }
--        else if (op & 32) {                     /* end-of-block */
--            Tracevv((stderr, "inflate:         end of block\n"));
--            state->mode = TYPE;
--            break;
--        }
--        else {
--            strm->msg = (char *)"invalid literal/length code";
--            state->mode = BAD;
--            break;
--        }
--    } while (in < last && out < end);
--
--    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
--    len = bits >> 3;
--    in -= len;
--    bits -= len << 3;
--    hold &= (1U << bits) - 1;
--
--    /* update state and return */
--    strm->next_in = in;
--    strm->next_out = out;
--    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
--    strm->avail_out = (unsigned)(out < end ?
--                                 257 + (end - out) : 257 - (out - end));
--    state->hold = hold;
--    state->bits = bits;
--    return;
--}
--
--/*
--   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
--   - Using bit fields for code structure
--   - Different op definition to avoid & for extra bits (do & for table bits)
--   - Three separate decoding do-loops for direct, window, and wnext == 0
--   - Special case for distance > 1 copies to do overlapped load and store copy
--   - Explicit branch predictions (based on measured branch probabilities)
--   - Deferring match copy and interspersed it with decoding subsequent codes
--   - Swapping literal/length else
--   - Swapping window/direct else
--   - Larger unrolled copy loops (three is about right)
--   - Moving len -= 3 statement into middle of loop
-- */
--
--#endif /* !ASMINF */
diff --cc zlib/inffast.h
index e5c1aa4ca8cd5244423680865609c71ab68f9ab6,e5c1aa4ca8cd5244423680865609c71ab68f9ab6..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,11 -1,11 +1,0 @@@
--/* inffast.h -- header to use inffast.c
-- * Copyright (C) 1995-2003, 2010 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* WARNING: this file should *not* be used by applications. It is
--   part of the implementation of the compression library and is
--   subject to change. Applications should only use zlib.h.
-- */
--
--void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
diff --cc zlib/inffixed.h
index d6283277694802ce7938f537f12990d6eead4924,d6283277694802ce7938f537f12990d6eead4924..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,94 -1,94 +1,0 @@@
--    /* inffixed.h -- table for decoding fixed codes
--     * Generated automatically by makefixed().
--     */
--
--    /* WARNING: this file should *not* be used by applications.
--       It is part of the implementation of this library and is
--       subject to change. Applications should only use zlib.h.
--     */
--
--    static const code lenfix[512] = {
--        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
--        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
--        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
--        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
--        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
--        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
--        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
--        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
--        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
--        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
--        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
--        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
--        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
--        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
--        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
--        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
--        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
--        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
--        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
--        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
--        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
--        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
--        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
--        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
--        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
--        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
--        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
--        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
--        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
--        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
--        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
--        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
--        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
--        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
--        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
--        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
--        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
--        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
--        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
--        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
--        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
--        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
--        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
--        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
--        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
--        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
--        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
--        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
--        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
--        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
--        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
--        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
--        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
--        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
--        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
--        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
--        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
--        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
--        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
--        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
--        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
--        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
--        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
--        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
--        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
--        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
--        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
--        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
--        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
--        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
--        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
--        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
--        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
--        {0,9,255}
--    };
--
--    static const code distfix[32] = {
--        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
--        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
--        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
--        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
--        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
--        {22,5,193},{64,5,0}
--    };
diff --cc zlib/inflate.c
index ac333e8c2edae90ec1145d06d9852002dd5d0617,ac333e8c2edae90ec1145d06d9852002dd5d0617..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1561 -1,1561 +1,0 @@@
--/* inflate.c -- zlib decompression
-- * Copyright (C) 1995-2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/*
-- * Change history:
-- *
-- * 1.2.beta0    24 Nov 2002
-- * - First version -- complete rewrite of inflate to simplify code, avoid
-- *   creation of window when not needed, minimize use of window when it is
-- *   needed, make inffast.c even faster, implement gzip decoding, and to
-- *   improve code readability and style over the previous zlib inflate code
-- *
-- * 1.2.beta1    25 Nov 2002
-- * - Use pointers for available input and output checking in inffast.c
-- * - Remove input and output counters in inffast.c
-- * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
-- * - Remove unnecessary second byte pull from length extra in inffast.c
-- * - Unroll direct copy to three copies per loop in inffast.c
-- *
-- * 1.2.beta2    4 Dec 2002
-- * - Change external routine names to reduce potential conflicts
-- * - Correct filename to inffixed.h for fixed tables in inflate.c
-- * - Make hbuf[] unsigned char to match parameter type in inflate.c
-- * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
-- *   to avoid negation problem on Alphas (64 bit) in inflate.c
-- *
-- * 1.2.beta3    22 Dec 2002
-- * - Add comments on state->bits assertion in inffast.c
-- * - Add comments on op field in inftrees.h
-- * - Fix bug in reuse of allocated window after inflateReset()
-- * - Remove bit fields--back to byte structure for speed
-- * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
-- * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
-- * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
-- * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
-- * - Use local copies of stream next and avail values, as well as local bit
-- *   buffer and bit count in inflate()--for speed when inflate_fast() not used
-- *
-- * 1.2.beta4    1 Jan 2003
-- * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
-- * - Move a comment on output buffer sizes from inffast.c to inflate.c
-- * - Add comments in inffast.c to introduce the inflate_fast() routine
-- * - Rearrange window copies in inflate_fast() for speed and simplification
-- * - Unroll last copy for window match in inflate_fast()
-- * - Use local copies of window variables in inflate_fast() for speed
-- * - Pull out common wnext == 0 case for speed in inflate_fast()
-- * - Make op and len in inflate_fast() unsigned for consistency
-- * - Add FAR to lcode and dcode declarations in inflate_fast()
-- * - Simplified bad distance check in inflate_fast()
-- * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
-- *   source file infback.c to provide a call-back interface to inflate for
-- *   programs like gzip and unzip -- uses window as output buffer to avoid
-- *   window copying
-- *
-- * 1.2.beta5    1 Jan 2003
-- * - Improved inflateBack() interface to allow the caller to provide initial
-- *   input in strm.
-- * - Fixed stored blocks bug in inflateBack()
-- *
-- * 1.2.beta6    4 Jan 2003
-- * - Added comments in inffast.c on effectiveness of POSTINC
-- * - Typecasting all around to reduce compiler warnings
-- * - Changed loops from while (1) or do {} while (1) to for (;;), again to
-- *   make compilers happy
-- * - Changed type of window in inflateBackInit() to unsigned char *
-- *
-- * 1.2.beta7    27 Jan 2003
-- * - Changed many types to unsigned or unsigned short to avoid warnings
-- * - Added inflateCopy() function
-- *
-- * 1.2.0        9 Mar 2003
-- * - Changed inflateBack() interface to provide separate opaque descriptors
-- *   for the in() and out() functions
-- * - Changed inflateBack() argument and in_func typedef to swap the length
-- *   and buffer address return values for the input function
-- * - Check next_in and next_out for Z_NULL on entry to inflate()
-- *
-- * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
-- */
--
--#include "zutil.h"
--#include "inftrees.h"
--#include "inflate.h"
--#include "inffast.h"
--
--#ifdef MAKEFIXED
--#  ifndef BUILDFIXED
--#    define BUILDFIXED
--#  endif
--#endif
--
--/* function prototypes */
--local int inflateStateCheck OF((z_streamp strm));
--local void fixedtables OF((struct inflate_state FAR *state));
--local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
--                           unsigned copy));
--#ifdef BUILDFIXED
--   void makefixed OF((void));
--#endif
--local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
--                              unsigned len));
--
--local int inflateStateCheck(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--    if (strm == Z_NULL ||
--        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
--        return 1;
--    state = (struct inflate_state FAR *)strm->state;
--    if (state == Z_NULL || state->strm != strm ||
--        state->mode < HEAD || state->mode > SYNC)
--        return 1;
--    return 0;
--}
--
--int ZEXPORT inflateResetKeep(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    strm->total_in = strm->total_out = state->total = 0;
--    strm->msg = Z_NULL;
--    if (state->wrap)        /* to support ill-conceived Java test suite */
--        strm->adler = state->wrap & 1;
--    state->mode = HEAD;
--    state->last = 0;
--    state->havedict = 0;
--    state->dmax = 32768U;
--    state->head = Z_NULL;
--    state->hold = 0;
--    state->bits = 0;
--    state->lencode = state->distcode = state->next = state->codes;
--    state->sane = 1;
--    state->back = -1;
--    Tracev((stderr, "inflate: reset\n"));
--    return Z_OK;
--}
--
--int ZEXPORT inflateReset(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    state->wsize = 0;
--    state->whave = 0;
--    state->wnext = 0;
--    return inflateResetKeep(strm);
--}
--
--int ZEXPORT inflateReset2(strm, windowBits)
--z_streamp strm;
--int windowBits;
--{
--    int wrap;
--    struct inflate_state FAR *state;
--
--    /* get the state */
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--
--    /* extract wrap request from windowBits parameter */
--    if (windowBits < 0) {
--        wrap = 0;
--        windowBits = -windowBits;
--    }
--    else {
--        wrap = (windowBits >> 4) + 5;
--#ifdef GUNZIP
--        if (windowBits < 48)
--            windowBits &= 15;
--#endif
--    }
--
--    /* set number of window bits, free window if different */
--    if (windowBits && (windowBits < 8 || windowBits > 15))
--        return Z_STREAM_ERROR;
--    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
--        ZFREE(strm, state->window);
--        state->window = Z_NULL;
--    }
--
--    /* update state and reset the rest of it */
--    state->wrap = wrap;
--    state->wbits = (unsigned)windowBits;
--    return inflateReset(strm);
--}
--
--int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
--z_streamp strm;
--int windowBits;
--const char *version;
--int stream_size;
--{
--    int ret;
--    struct inflate_state FAR *state;
--
--    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
--        stream_size != (int)(sizeof(z_stream)))
--        return Z_VERSION_ERROR;
--    if (strm == Z_NULL) return Z_STREAM_ERROR;
--    strm->msg = Z_NULL;                 /* in case we return an error */
--    if (strm->zalloc == (alloc_func)0) {
--#ifdef Z_SOLO
--        return Z_STREAM_ERROR;
--#else
--        strm->zalloc = zcalloc;
--        strm->opaque = (voidpf)0;
--#endif
--    }
--    if (strm->zfree == (free_func)0)
--#ifdef Z_SOLO
--        return Z_STREAM_ERROR;
--#else
--        strm->zfree = zcfree;
--#endif
--    state = (struct inflate_state FAR *)
--            ZALLOC(strm, 1, sizeof(struct inflate_state));
--    if (state == Z_NULL) return Z_MEM_ERROR;
--    Tracev((stderr, "inflate: allocated\n"));
--    strm->state = (struct internal_state FAR *)state;
--    state->strm = strm;
--    state->window = Z_NULL;
--    state->mode = HEAD;     /* to pass state test in inflateReset2() */
--    ret = inflateReset2(strm, windowBits);
--    if (ret != Z_OK) {
--        ZFREE(strm, state);
--        strm->state = Z_NULL;
--    }
--    return ret;
--}
--
--int ZEXPORT inflateInit_(strm, version, stream_size)
--z_streamp strm;
--const char *version;
--int stream_size;
--{
--    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
--}
--
--int ZEXPORT inflatePrime(strm, bits, value)
--z_streamp strm;
--int bits;
--int value;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    if (bits < 0) {
--        state->hold = 0;
--        state->bits = 0;
--        return Z_OK;
--    }
--    if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
--    value &= (1L << bits) - 1;
--    state->hold += (unsigned)value << state->bits;
--    state->bits += (uInt)bits;
--    return Z_OK;
--}
--
--/*
--   Return state with length and distance decoding tables and index sizes set to
--   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
--   If BUILDFIXED is defined, then instead this routine builds the tables the
--   first time it's called, and returns those tables the first time and
--   thereafter.  This reduces the size of the code by about 2K bytes, in
--   exchange for a little execution time.  However, BUILDFIXED should not be
--   used for threaded applications, since the rewriting of the tables and virgin
--   may not be thread-safe.
-- */
--local void fixedtables(state)
--struct inflate_state FAR *state;
--{
--#ifdef BUILDFIXED
--    static int virgin = 1;
--    static code *lenfix, *distfix;
--    static code fixed[544];
--
--    /* build fixed huffman tables if first call (may not be thread safe) */
--    if (virgin) {
--        unsigned sym, bits;
--        static code *next;
--
--        /* literal/length table */
--        sym = 0;
--        while (sym < 144) state->lens[sym++] = 8;
--        while (sym < 256) state->lens[sym++] = 9;
--        while (sym < 280) state->lens[sym++] = 7;
--        while (sym < 288) state->lens[sym++] = 8;
--        next = fixed;
--        lenfix = next;
--        bits = 9;
--        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
--
--        /* distance table */
--        sym = 0;
--        while (sym < 32) state->lens[sym++] = 5;
--        distfix = next;
--        bits = 5;
--        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
--
--        /* do this just once */
--        virgin = 0;
--    }
--#else /* !BUILDFIXED */
--#   include "inffixed.h"
--#endif /* BUILDFIXED */
--    state->lencode = lenfix;
--    state->lenbits = 9;
--    state->distcode = distfix;
--    state->distbits = 5;
--}
--
--#ifdef MAKEFIXED
--#include <stdio.h>
--
--/*
--   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
--   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
--   those tables to stdout, which would be piped to inffixed.h.  A small program
--   can simply call makefixed to do this:
--
--    void makefixed(void);
--
--    int main(void)
--    {
--        makefixed();
--        return 0;
--    }
--
--   Then that can be linked with zlib built with MAKEFIXED defined and run:
--
--    a.out > inffixed.h
-- */
--void makefixed()
--{
--    unsigned low, size;
--    struct inflate_state state;
--
--    fixedtables(&state);
--    puts("    /* inffixed.h -- table for decoding fixed codes");
--    puts("     * Generated automatically by makefixed().");
--    puts("     */");
--    puts("");
--    puts("    /* WARNING: this file should *not* be used by applications.");
--    puts("       It is part of the implementation of this library and is");
--    puts("       subject to change. Applications should only use zlib.h.");
--    puts("     */");
--    puts("");
--    size = 1U << 9;
--    printf("    static const code lenfix[%u] = {", size);
--    low = 0;
--    for (;;) {
--        if ((low % 7) == 0) printf("\n        ");
--        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
--               state.lencode[low].bits, state.lencode[low].val);
--        if (++low == size) break;
--        putchar(',');
--    }
--    puts("\n    };");
--    size = 1U << 5;
--    printf("\n    static const code distfix[%u] = {", size);
--    low = 0;
--    for (;;) {
--        if ((low % 6) == 0) printf("\n        ");
--        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
--               state.distcode[low].val);
--        if (++low == size) break;
--        putchar(',');
--    }
--    puts("\n    };");
--}
--#endif /* MAKEFIXED */
--
--/*
--   Update the window with the last wsize (normally 32K) bytes written before
--   returning.  If window does not exist yet, create it.  This is only called
--   when a window is already in use, or when output has been written during this
--   inflate call, but the end of the deflate stream has not been reached yet.
--   It is also called to create a window for dictionary data when a dictionary
--   is loaded.
--
--   Providing output buffers larger than 32K to inflate() should provide a speed
--   advantage, since only the last 32K of output is copied to the sliding window
--   upon return from inflate(), and since all distances after the first 32K of
--   output will fall in the output data, making match copies simpler and faster.
--   The advantage may be dependent on the size of the processor's data caches.
-- */
--local int updatewindow(strm, end, copy)
--z_streamp strm;
--const Bytef *end;
--unsigned copy;
--{
--    struct inflate_state FAR *state;
--    unsigned dist;
--
--    state = (struct inflate_state FAR *)strm->state;
--
--    /* if it hasn't been done already, allocate space for the window */
--    if (state->window == Z_NULL) {
--        state->window = (unsigned char FAR *)
--                        ZALLOC(strm, 1U << state->wbits,
--                               sizeof(unsigned char));
--        if (state->window == Z_NULL) return 1;
--    }
--
--    /* if window not in use yet, initialize */
--    if (state->wsize == 0) {
--        state->wsize = 1U << state->wbits;
--        state->wnext = 0;
--        state->whave = 0;
--    }
--
--    /* copy state->wsize or less output bytes into the circular window */
--    if (copy >= state->wsize) {
--        zmemcpy(state->window, end - state->wsize, state->wsize);
--        state->wnext = 0;
--        state->whave = state->wsize;
--    }
--    else {
--        dist = state->wsize - state->wnext;
--        if (dist > copy) dist = copy;
--        zmemcpy(state->window + state->wnext, end - copy, dist);
--        copy -= dist;
--        if (copy) {
--            zmemcpy(state->window, end - copy, copy);
--            state->wnext = copy;
--            state->whave = state->wsize;
--        }
--        else {
--            state->wnext += dist;
--            if (state->wnext == state->wsize) state->wnext = 0;
--            if (state->whave < state->wsize) state->whave += dist;
--        }
--    }
--    return 0;
--}
--
--/* Macros for inflate(): */
--
--/* check function to use adler32() for zlib or crc32() for gzip */
--#ifdef GUNZIP
--#  define UPDATE(check, buf, len) \
--    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
--#else
--#  define UPDATE(check, buf, len) adler32(check, buf, len)
--#endif
--
--/* check macros for header crc */
--#ifdef GUNZIP
--#  define CRC2(check, word) \
--    do { \
--        hbuf[0] = (unsigned char)(word); \
--        hbuf[1] = (unsigned char)((word) >> 8); \
--        check = crc32(check, hbuf, 2); \
--    } while (0)
--
--#  define CRC4(check, word) \
--    do { \
--        hbuf[0] = (unsigned char)(word); \
--        hbuf[1] = (unsigned char)((word) >> 8); \
--        hbuf[2] = (unsigned char)((word) >> 16); \
--        hbuf[3] = (unsigned char)((word) >> 24); \
--        check = crc32(check, hbuf, 4); \
--    } while (0)
--#endif
--
--/* Load registers with state in inflate() for speed */
--#define LOAD() \
--    do { \
--        put = strm->next_out; \
--        left = strm->avail_out; \
--        next = strm->next_in; \
--        have = strm->avail_in; \
--        hold = state->hold; \
--        bits = state->bits; \
--    } while (0)
--
--/* Restore state from registers in inflate() */
--#define RESTORE() \
--    do { \
--        strm->next_out = put; \
--        strm->avail_out = left; \
--        strm->next_in = next; \
--        strm->avail_in = have; \
--        state->hold = hold; \
--        state->bits = bits; \
--    } while (0)
--
--/* Clear the input bit accumulator */
--#define INITBITS() \
--    do { \
--        hold = 0; \
--        bits = 0; \
--    } while (0)
--
--/* Get a byte of input into the bit accumulator, or return from inflate()
--   if there is no input available. */
--#define PULLBYTE() \
--    do { \
--        if (have == 0) goto inf_leave; \
--        have--; \
--        hold += (unsigned long)(*next++) << bits; \
--        bits += 8; \
--    } while (0)
--
--/* Assure that there are at least n bits in the bit accumulator.  If there is
--   not enough available input to do that, then return from inflate(). */
--#define NEEDBITS(n) \
--    do { \
--        while (bits < (unsigned)(n)) \
--            PULLBYTE(); \
--    } while (0)
--
--/* Return the low n bits of the bit accumulator (n < 16) */
--#define BITS(n) \
--    ((unsigned)hold & ((1U << (n)) - 1))
--
--/* Remove n bits from the bit accumulator */
--#define DROPBITS(n) \
--    do { \
--        hold >>= (n); \
--        bits -= (unsigned)(n); \
--    } while (0)
--
--/* Remove zero to seven bits as needed to go to a byte boundary */
--#define BYTEBITS() \
--    do { \
--        hold >>= bits & 7; \
--        bits -= bits & 7; \
--    } while (0)
--
--/*
--   inflate() uses a state machine to process as much input data and generate as
--   much output data as possible before returning.  The state machine is
--   structured roughly as follows:
--
--    for (;;) switch (state) {
--    ...
--    case STATEn:
--        if (not enough input data or output space to make progress)
--            return;
--        ... make progress ...
--        state = STATEm;
--        break;
--    ...
--    }
--
--   so when inflate() is called again, the same case is attempted again, and
--   if the appropriate resources are provided, the machine proceeds to the
--   next state.  The NEEDBITS() macro is usually the way the state evaluates
--   whether it can proceed or should return.  NEEDBITS() does the return if
--   the requested bits are not available.  The typical use of the BITS macros
--   is:
--
--        NEEDBITS(n);
--        ... do something with BITS(n) ...
--        DROPBITS(n);
--
--   where NEEDBITS(n) either returns from inflate() if there isn't enough
--   input left to load n bits into the accumulator, or it continues.  BITS(n)
--   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
--   the low n bits off the accumulator.  INITBITS() clears the accumulator
--   and sets the number of available bits to zero.  BYTEBITS() discards just
--   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
--   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
--
--   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
--   if there is no input available.  The decoding of variable length codes uses
--   PULLBYTE() directly in order to pull just enough bytes to decode the next
--   code, and no more.
--
--   Some states loop until they get enough input, making sure that enough
--   state information is maintained to continue the loop where it left off
--   if NEEDBITS() returns in the loop.  For example, want, need, and keep
--   would all have to actually be part of the saved state in case NEEDBITS()
--   returns:
--
--    case STATEw:
--        while (want < need) {
--            NEEDBITS(n);
--            keep[want++] = BITS(n);
--            DROPBITS(n);
--        }
--        state = STATEx;
--    case STATEx:
--
--   As shown above, if the next state is also the next case, then the break
--   is omitted.
--
--   A state may also return if there is not enough output space available to
--   complete that state.  Those states are copying stored data, writing a
--   literal byte, and copying a matching string.
--
--   When returning, a "goto inf_leave" is used to update the total counters,
--   update the check value, and determine whether any progress has been made
--   during that inflate() call in order to return the proper return code.
--   Progress is defined as a change in either strm->avail_in or strm->avail_out.
--   When there is a window, goto inf_leave will update the window with the last
--   output written.  If a goto inf_leave occurs in the middle of decompression
--   and there is no window currently, goto inf_leave will create one and copy
--   output to the window for the next call of inflate().
--
--   In this implementation, the flush parameter of inflate() only affects the
--   return code (per zlib.h).  inflate() always writes as much as possible to
--   strm->next_out, given the space available and the provided input--the effect
--   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
--   the allocation of and copying into a sliding window until necessary, which
--   provides the effect documented in zlib.h for Z_FINISH when the entire input
--   stream available.  So the only thing the flush parameter actually does is:
--   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
--   will return Z_BUF_ERROR if it has not reached the end of the stream.
-- */
--
--int ZEXPORT inflate(strm, flush)
--z_streamp strm;
--int flush;
--{
--    struct inflate_state FAR *state;
--    z_const unsigned char FAR *next;    /* next input */
--    unsigned char FAR *put;     /* next output */
--    unsigned have, left;        /* available input and output */
--    unsigned long hold;         /* bit buffer */
--    unsigned bits;              /* bits in bit buffer */
--    unsigned in, out;           /* save starting available input and output */
--    unsigned copy;              /* number of stored or match bytes to copy */
--    unsigned char FAR *from;    /* where to copy match bytes from */
--    code here;                  /* current decoding table entry */
--    code last;                  /* parent table entry */
--    unsigned len;               /* length to copy for repeats, bits to drop */
--    int ret;                    /* return code */
--#ifdef GUNZIP
--    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
--#endif
--    static const unsigned short order[19] = /* permutation of code lengths */
--        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
--
--    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
--        (strm->next_in == Z_NULL && strm->avail_in != 0))
--        return Z_STREAM_ERROR;
--
--    state = (struct inflate_state FAR *)strm->state;
--    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
--    LOAD();
--    in = have;
--    out = left;
--    ret = Z_OK;
--    for (;;)
--        switch (state->mode) {
--        case HEAD:
--            if (state->wrap == 0) {
--                state->mode = TYPEDO;
--                break;
--            }
--            NEEDBITS(16);
--#ifdef GUNZIP
--            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
--                if (state->wbits == 0)
--                    state->wbits = 15;
--                state->check = crc32(0L, Z_NULL, 0);
--                CRC2(state->check, hold);
--                INITBITS();
--                state->mode = FLAGS;
--                break;
--            }
--            state->flags = 0;           /* expect zlib header */
--            if (state->head != Z_NULL)
--                state->head->done = -1;
--            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
--#else
--            if (
--#endif
--                ((BITS(8) << 8) + (hold >> 8)) % 31) {
--                strm->msg = (char *)"incorrect header check";
--                state->mode = BAD;
--                break;
--            }
--            if (BITS(4) != Z_DEFLATED) {
--                strm->msg = (char *)"unknown compression method";
--                state->mode = BAD;
--                break;
--            }
--            DROPBITS(4);
--            len = BITS(4) + 8;
--            if (state->wbits == 0)
--                state->wbits = len;
--            if (len > 15 || len > state->wbits) {
--                strm->msg = (char *)"invalid window size";
--                state->mode = BAD;
--                break;
--            }
--            state->dmax = 1U << len;
--            Tracev((stderr, "inflate:   zlib header ok\n"));
--            strm->adler = state->check = adler32(0L, Z_NULL, 0);
--            state->mode = hold & 0x200 ? DICTID : TYPE;
--            INITBITS();
--            break;
--#ifdef GUNZIP
--        case FLAGS:
--            NEEDBITS(16);
--            state->flags = (int)(hold);
--            if ((state->flags & 0xff) != Z_DEFLATED) {
--                strm->msg = (char *)"unknown compression method";
--                state->mode = BAD;
--                break;
--            }
--            if (state->flags & 0xe000) {
--                strm->msg = (char *)"unknown header flags set";
--                state->mode = BAD;
--                break;
--            }
--            if (state->head != Z_NULL)
--                state->head->text = (int)((hold >> 8) & 1);
--            if ((state->flags & 0x0200) && (state->wrap & 4))
--                CRC2(state->check, hold);
--            INITBITS();
--            state->mode = TIME;
--        case TIME:
--            NEEDBITS(32);
--            if (state->head != Z_NULL)
--                state->head->time = hold;
--            if ((state->flags & 0x0200) && (state->wrap & 4))
--                CRC4(state->check, hold);
--            INITBITS();
--            state->mode = OS;
--        case OS:
--            NEEDBITS(16);
--            if (state->head != Z_NULL) {
--                state->head->xflags = (int)(hold & 0xff);
--                state->head->os = (int)(hold >> 8);
--            }
--            if ((state->flags & 0x0200) && (state->wrap & 4))
--                CRC2(state->check, hold);
--            INITBITS();
--            state->mode = EXLEN;
--        case EXLEN:
--            if (state->flags & 0x0400) {
--                NEEDBITS(16);
--                state->length = (unsigned)(hold);
--                if (state->head != Z_NULL)
--                    state->head->extra_len = (unsigned)hold;
--                if ((state->flags & 0x0200) && (state->wrap & 4))
--                    CRC2(state->check, hold);
--                INITBITS();
--            }
--            else if (state->head != Z_NULL)
--                state->head->extra = Z_NULL;
--            state->mode = EXTRA;
--        case EXTRA:
--            if (state->flags & 0x0400) {
--                copy = state->length;
--                if (copy > have) copy = have;
--                if (copy) {
--                    if (state->head != Z_NULL &&
--                        state->head->extra != Z_NULL) {
--                        len = state->head->extra_len - state->length;
--                        zmemcpy(state->head->extra + len, next,
--                                len + copy > state->head->extra_max ?
--                                state->head->extra_max - len : copy);
--                    }
--                    if ((state->flags & 0x0200) && (state->wrap & 4))
--                        state->check = crc32(state->check, next, copy);
--                    have -= copy;
--                    next += copy;
--                    state->length -= copy;
--                }
--                if (state->length) goto inf_leave;
--            }
--            state->length = 0;
--            state->mode = NAME;
--        case NAME:
--            if (state->flags & 0x0800) {
--                if (have == 0) goto inf_leave;
--                copy = 0;
--                do {
--                    len = (unsigned)(next[copy++]);
--                    if (state->head != Z_NULL &&
--                            state->head->name != Z_NULL &&
--                            state->length < state->head->name_max)
--                        state->head->name[state->length++] = (Bytef)len;
--                } while (len && copy < have);
--                if ((state->flags & 0x0200) && (state->wrap & 4))
--                    state->check = crc32(state->check, next, copy);
--                have -= copy;
--                next += copy;
--                if (len) goto inf_leave;
--            }
--            else if (state->head != Z_NULL)
--                state->head->name = Z_NULL;
--            state->length = 0;
--            state->mode = COMMENT;
--        case COMMENT:
--            if (state->flags & 0x1000) {
--                if (have == 0) goto inf_leave;
--                copy = 0;
--                do {
--                    len = (unsigned)(next[copy++]);
--                    if (state->head != Z_NULL &&
--                            state->head->comment != Z_NULL &&
--                            state->length < state->head->comm_max)
--                        state->head->comment[state->length++] = (Bytef)len;
--                } while (len && copy < have);
--                if ((state->flags & 0x0200) && (state->wrap & 4))
--                    state->check = crc32(state->check, next, copy);
--                have -= copy;
--                next += copy;
--                if (len) goto inf_leave;
--            }
--            else if (state->head != Z_NULL)
--                state->head->comment = Z_NULL;
--            state->mode = HCRC;
--        case HCRC:
--            if (state->flags & 0x0200) {
--                NEEDBITS(16);
--                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
--                    strm->msg = (char *)"header crc mismatch";
--                    state->mode = BAD;
--                    break;
--                }
--                INITBITS();
--            }
--            if (state->head != Z_NULL) {
--                state->head->hcrc = (int)((state->flags >> 9) & 1);
--                state->head->done = 1;
--            }
--            strm->adler = state->check = crc32(0L, Z_NULL, 0);
--            state->mode = TYPE;
--            break;
--#endif
--        case DICTID:
--            NEEDBITS(32);
--            strm->adler = state->check = ZSWAP32(hold);
--            INITBITS();
--            state->mode = DICT;
--        case DICT:
--            if (state->havedict == 0) {
--                RESTORE();
--                return Z_NEED_DICT;
--            }
--            strm->adler = state->check = adler32(0L, Z_NULL, 0);
--            state->mode = TYPE;
--        case TYPE:
--            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
--        case TYPEDO:
--            if (state->last) {
--                BYTEBITS();
--                state->mode = CHECK;
--                break;
--            }
--            NEEDBITS(3);
--            state->last = BITS(1);
--            DROPBITS(1);
--            switch (BITS(2)) {
--            case 0:                             /* stored block */
--                Tracev((stderr, "inflate:     stored block%s\n",
--                        state->last ? " (last)" : ""));
--                state->mode = STORED;
--                break;
--            case 1:                             /* fixed block */
--                fixedtables(state);
--                Tracev((stderr, "inflate:     fixed codes block%s\n",
--                        state->last ? " (last)" : ""));
--                state->mode = LEN_;             /* decode codes */
--                if (flush == Z_TREES) {
--                    DROPBITS(2);
--                    goto inf_leave;
--                }
--                break;
--            case 2:                             /* dynamic block */
--                Tracev((stderr, "inflate:     dynamic codes block%s\n",
--                        state->last ? " (last)" : ""));
--                state->mode = TABLE;
--                break;
--            case 3:
--                strm->msg = (char *)"invalid block type";
--                state->mode = BAD;
--            }
--            DROPBITS(2);
--            break;
--        case STORED:
--            BYTEBITS();                         /* go to byte boundary */
--            NEEDBITS(32);
--            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
--                strm->msg = (char *)"invalid stored block lengths";
--                state->mode = BAD;
--                break;
--            }
--            state->length = (unsigned)hold & 0xffff;
--            Tracev((stderr, "inflate:       stored length %u\n",
--                    state->length));
--            INITBITS();
--            state->mode = COPY_;
--            if (flush == Z_TREES) goto inf_leave;
--        case COPY_:
--            state->mode = COPY;
--        case COPY:
--            copy = state->length;
--            if (copy) {
--                if (copy > have) copy = have;
--                if (copy > left) copy = left;
--                if (copy == 0) goto inf_leave;
--                zmemcpy(put, next, copy);
--                have -= copy;
--                next += copy;
--                left -= copy;
--                put += copy;
--                state->length -= copy;
--                break;
--            }
--            Tracev((stderr, "inflate:       stored end\n"));
--            state->mode = TYPE;
--            break;
--        case TABLE:
--            NEEDBITS(14);
--            state->nlen = BITS(5) + 257;
--            DROPBITS(5);
--            state->ndist = BITS(5) + 1;
--            DROPBITS(5);
--            state->ncode = BITS(4) + 4;
--            DROPBITS(4);
--#ifndef PKZIP_BUG_WORKAROUND
--            if (state->nlen > 286 || state->ndist > 30) {
--                strm->msg = (char *)"too many length or distance symbols";
--                state->mode = BAD;
--                break;
--            }
--#endif
--            Tracev((stderr, "inflate:       table sizes ok\n"));
--            state->have = 0;
--            state->mode = LENLENS;
--        case LENLENS:
--            while (state->have < state->ncode) {
--                NEEDBITS(3);
--                state->lens[order[state->have++]] = (unsigned short)BITS(3);
--                DROPBITS(3);
--            }
--            while (state->have < 19)
--                state->lens[order[state->have++]] = 0;
--            state->next = state->codes;
--            state->lencode = (const code FAR *)(state->next);
--            state->lenbits = 7;
--            ret = inflate_table(CODES, state->lens, 19, &(state->next),
--                                &(state->lenbits), state->work);
--            if (ret) {
--                strm->msg = (char *)"invalid code lengths set";
--                state->mode = BAD;
--                break;
--            }
--            Tracev((stderr, "inflate:       code lengths ok\n"));
--            state->have = 0;
--            state->mode = CODELENS;
--        case CODELENS:
--            while (state->have < state->nlen + state->ndist) {
--                for (;;) {
--                    here = state->lencode[BITS(state->lenbits)];
--                    if ((unsigned)(here.bits) <= bits) break;
--                    PULLBYTE();
--                }
--                if (here.val < 16) {
--                    DROPBITS(here.bits);
--                    state->lens[state->have++] = here.val;
--                }
--                else {
--                    if (here.val == 16) {
--                        NEEDBITS(here.bits + 2);
--                        DROPBITS(here.bits);
--                        if (state->have == 0) {
--                            strm->msg = (char *)"invalid bit length repeat";
--                            state->mode = BAD;
--                            break;
--                        }
--                        len = state->lens[state->have - 1];
--                        copy = 3 + BITS(2);
--                        DROPBITS(2);
--                    }
--                    else if (here.val == 17) {
--                        NEEDBITS(here.bits + 3);
--                        DROPBITS(here.bits);
--                        len = 0;
--                        copy = 3 + BITS(3);
--                        DROPBITS(3);
--                    }
--                    else {
--                        NEEDBITS(here.bits + 7);
--                        DROPBITS(here.bits);
--                        len = 0;
--                        copy = 11 + BITS(7);
--                        DROPBITS(7);
--                    }
--                    if (state->have + copy > state->nlen + state->ndist) {
--                        strm->msg = (char *)"invalid bit length repeat";
--                        state->mode = BAD;
--                        break;
--                    }
--                    while (copy--)
--                        state->lens[state->have++] = (unsigned short)len;
--                }
--            }
--
--            /* handle error breaks in while */
--            if (state->mode == BAD) break;
--
--            /* check for end-of-block code (better have one) */
--            if (state->lens[256] == 0) {
--                strm->msg = (char *)"invalid code -- missing end-of-block";
--                state->mode = BAD;
--                break;
--            }
--
--            /* build code tables -- note: do not change the lenbits or distbits
--               values here (9 and 6) without reading the comments in inftrees.h
--               concerning the ENOUGH constants, which depend on those values */
--            state->next = state->codes;
--            state->lencode = (const code FAR *)(state->next);
--            state->lenbits = 9;
--            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
--                                &(state->lenbits), state->work);
--            if (ret) {
--                strm->msg = (char *)"invalid literal/lengths set";
--                state->mode = BAD;
--                break;
--            }
--            state->distcode = (const code FAR *)(state->next);
--            state->distbits = 6;
--            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
--                            &(state->next), &(state->distbits), state->work);
--            if (ret) {
--                strm->msg = (char *)"invalid distances set";
--                state->mode = BAD;
--                break;
--            }
--            Tracev((stderr, "inflate:       codes ok\n"));
--            state->mode = LEN_;
--            if (flush == Z_TREES) goto inf_leave;
--        case LEN_:
--            state->mode = LEN;
--        case LEN:
--            if (have >= 6 && left >= 258) {
--                RESTORE();
--                inflate_fast(strm, out);
--                LOAD();
--                if (state->mode == TYPE)
--                    state->back = -1;
--                break;
--            }
--            state->back = 0;
--            for (;;) {
--                here = state->lencode[BITS(state->lenbits)];
--                if ((unsigned)(here.bits) <= bits) break;
--                PULLBYTE();
--            }
--            if (here.op && (here.op & 0xf0) == 0) {
--                last = here;
--                for (;;) {
--                    here = state->lencode[last.val +
--                            (BITS(last.bits + last.op) >> last.bits)];
--                    if ((unsigned)(last.bits + here.bits) <= bits) break;
--                    PULLBYTE();
--                }
--                DROPBITS(last.bits);
--                state->back += last.bits;
--            }
--            DROPBITS(here.bits);
--            state->back += here.bits;
--            state->length = (unsigned)here.val;
--            if ((int)(here.op) == 0) {
--                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
--                        "inflate:         literal '%c'\n" :
--                        "inflate:         literal 0x%02x\n", here.val));
--                state->mode = LIT;
--                break;
--            }
--            if (here.op & 32) {
--                Tracevv((stderr, "inflate:         end of block\n"));
--                state->back = -1;
--                state->mode = TYPE;
--                break;
--            }
--            if (here.op & 64) {
--                strm->msg = (char *)"invalid literal/length code";
--                state->mode = BAD;
--                break;
--            }
--            state->extra = (unsigned)(here.op) & 15;
--            state->mode = LENEXT;
--        case LENEXT:
--            if (state->extra) {
--                NEEDBITS(state->extra);
--                state->length += BITS(state->extra);
--                DROPBITS(state->extra);
--                state->back += state->extra;
--            }
--            Tracevv((stderr, "inflate:         length %u\n", state->length));
--            state->was = state->length;
--            state->mode = DIST;
--        case DIST:
--            for (;;) {
--                here = state->distcode[BITS(state->distbits)];
--                if ((unsigned)(here.bits) <= bits) break;
--                PULLBYTE();
--            }
--            if ((here.op & 0xf0) == 0) {
--                last = here;
--                for (;;) {
--                    here = state->distcode[last.val +
--                            (BITS(last.bits + last.op) >> last.bits)];
--                    if ((unsigned)(last.bits + here.bits) <= bits) break;
--                    PULLBYTE();
--                }
--                DROPBITS(last.bits);
--                state->back += last.bits;
--            }
--            DROPBITS(here.bits);
--            state->back += here.bits;
--            if (here.op & 64) {
--                strm->msg = (char *)"invalid distance code";
--                state->mode = BAD;
--                break;
--            }
--            state->offset = (unsigned)here.val;
--            state->extra = (unsigned)(here.op) & 15;
--            state->mode = DISTEXT;
--        case DISTEXT:
--            if (state->extra) {
--                NEEDBITS(state->extra);
--                state->offset += BITS(state->extra);
--                DROPBITS(state->extra);
--                state->back += state->extra;
--            }
--#ifdef INFLATE_STRICT
--            if (state->offset > state->dmax) {
--                strm->msg = (char *)"invalid distance too far back";
--                state->mode = BAD;
--                break;
--            }
--#endif
--            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
--            state->mode = MATCH;
--        case MATCH:
--            if (left == 0) goto inf_leave;
--            copy = out - left;
--            if (state->offset > copy) {         /* copy from window */
--                copy = state->offset - copy;
--                if (copy > state->whave) {
--                    if (state->sane) {
--                        strm->msg = (char *)"invalid distance too far back";
--                        state->mode = BAD;
--                        break;
--                    }
--#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
--                    Trace((stderr, "inflate.c too far\n"));
--                    copy -= state->whave;
--                    if (copy > state->length) copy = state->length;
--                    if (copy > left) copy = left;
--                    left -= copy;
--                    state->length -= copy;
--                    do {
--                        *put++ = 0;
--                    } while (--copy);
--                    if (state->length == 0) state->mode = LEN;
--                    break;
--#endif
--                }
--                if (copy > state->wnext) {
--                    copy -= state->wnext;
--                    from = state->window + (state->wsize - copy);
--                }
--                else
--                    from = state->window + (state->wnext - copy);
--                if (copy > state->length) copy = state->length;
--            }
--            else {                              /* copy from output */
--                from = put - state->offset;
--                copy = state->length;
--            }
--            if (copy > left) copy = left;
--            left -= copy;
--            state->length -= copy;
--            do {
--                *put++ = *from++;
--            } while (--copy);
--            if (state->length == 0) state->mode = LEN;
--            break;
--        case LIT:
--            if (left == 0) goto inf_leave;
--            *put++ = (unsigned char)(state->length);
--            left--;
--            state->mode = LEN;
--            break;
--        case CHECK:
--            if (state->wrap) {
--                NEEDBITS(32);
--                out -= left;
--                strm->total_out += out;
--                state->total += out;
--                if ((state->wrap & 4) && out)
--                    strm->adler = state->check =
--                        UPDATE(state->check, put - out, out);
--                out = left;
--                if ((state->wrap & 4) && (
--#ifdef GUNZIP
--                     state->flags ? hold :
--#endif
--                     ZSWAP32(hold)) != state->check) {
--                    strm->msg = (char *)"incorrect data check";
--                    state->mode = BAD;
--                    break;
--                }
--                INITBITS();
--                Tracev((stderr, "inflate:   check matches trailer\n"));
--            }
--#ifdef GUNZIP
--            state->mode = LENGTH;
--        case LENGTH:
--            if (state->wrap && state->flags) {
--                NEEDBITS(32);
--                if (hold != (state->total & 0xffffffffUL)) {
--                    strm->msg = (char *)"incorrect length check";
--                    state->mode = BAD;
--                    break;
--                }
--                INITBITS();
--                Tracev((stderr, "inflate:   length matches trailer\n"));
--            }
--#endif
--            state->mode = DONE;
--        case DONE:
--            ret = Z_STREAM_END;
--            goto inf_leave;
--        case BAD:
--            ret = Z_DATA_ERROR;
--            goto inf_leave;
--        case MEM:
--            return Z_MEM_ERROR;
--        case SYNC:
--        default:
--            return Z_STREAM_ERROR;
--        }
--
--    /*
--       Return from inflate(), updating the total counts and the check value.
--       If there was no progress during the inflate() call, return a buffer
--       error.  Call updatewindow() to create and/or update the window state.
--       Note: a memory error from inflate() is non-recoverable.
--     */
--  inf_leave:
--    RESTORE();
--    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
--            (state->mode < CHECK || flush != Z_FINISH)))
--        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
--            state->mode = MEM;
--            return Z_MEM_ERROR;
--        }
--    in -= strm->avail_in;
--    out -= strm->avail_out;
--    strm->total_in += in;
--    strm->total_out += out;
--    state->total += out;
--    if ((state->wrap & 4) && out)
--        strm->adler = state->check =
--            UPDATE(state->check, strm->next_out - out, out);
--    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
--                      (state->mode == TYPE ? 128 : 0) +
--                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
--    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
--        ret = Z_BUF_ERROR;
--    return ret;
--}
--
--int ZEXPORT inflateEnd(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--    if (inflateStateCheck(strm))
--        return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    if (state->window != Z_NULL) ZFREE(strm, state->window);
--    ZFREE(strm, strm->state);
--    strm->state = Z_NULL;
--    Tracev((stderr, "inflate: end\n"));
--    return Z_OK;
--}
--
--int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)
--z_streamp strm;
--Bytef *dictionary;
--uInt *dictLength;
--{
--    struct inflate_state FAR *state;
--
--    /* check state */
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--
--    /* copy dictionary */
--    if (state->whave && dictionary != Z_NULL) {
--        zmemcpy(dictionary, state->window + state->wnext,
--                state->whave - state->wnext);
--        zmemcpy(dictionary + state->whave - state->wnext,
--                state->window, state->wnext);
--    }
--    if (dictLength != Z_NULL)
--        *dictLength = state->whave;
--    return Z_OK;
--}
--
--int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
--z_streamp strm;
--const Bytef *dictionary;
--uInt dictLength;
--{
--    struct inflate_state FAR *state;
--    unsigned long dictid;
--    int ret;
--
--    /* check state */
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    if (state->wrap != 0 && state->mode != DICT)
--        return Z_STREAM_ERROR;
--
--    /* check for correct dictionary identifier */
--    if (state->mode == DICT) {
--        dictid = adler32(0L, Z_NULL, 0);
--        dictid = adler32(dictid, dictionary, dictLength);
--        if (dictid != state->check)
--            return Z_DATA_ERROR;
--    }
--
--    /* copy dictionary to window using updatewindow(), which will amend the
--       existing dictionary if appropriate */
--    ret = updatewindow(strm, dictionary + dictLength, dictLength);
--    if (ret) {
--        state->mode = MEM;
--        return Z_MEM_ERROR;
--    }
--    state->havedict = 1;
--    Tracev((stderr, "inflate:   dictionary set\n"));
--    return Z_OK;
--}
--
--int ZEXPORT inflateGetHeader(strm, head)
--z_streamp strm;
--gz_headerp head;
--{
--    struct inflate_state FAR *state;
--
--    /* check state */
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
--
--    /* save header structure */
--    state->head = head;
--    head->done = 0;
--    return Z_OK;
--}
--
--/*
--   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
--   or when out of input.  When called, *have is the number of pattern bytes
--   found in order so far, in 0..3.  On return *have is updated to the new
--   state.  If on return *have equals four, then the pattern was found and the
--   return value is how many bytes were read including the last byte of the
--   pattern.  If *have is less than four, then the pattern has not been found
--   yet and the return value is len.  In the latter case, syncsearch() can be
--   called again with more data and the *have state.  *have is initialized to
--   zero for the first call.
-- */
--local unsigned syncsearch(have, buf, len)
--unsigned FAR *have;
--const unsigned char FAR *buf;
--unsigned len;
--{
--    unsigned got;
--    unsigned next;
--
--    got = *have;
--    next = 0;
--    while (next < len && got < 4) {
--        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
--            got++;
--        else if (buf[next])
--            got = 0;
--        else
--            got = 4 - got;
--        next++;
--    }
--    *have = got;
--    return next;
--}
--
--int ZEXPORT inflateSync(strm)
--z_streamp strm;
--{
--    unsigned len;               /* number of bytes to look at or looked at */
--    unsigned long in, out;      /* temporary to save total_in and total_out */
--    unsigned char buf[4];       /* to restore bit buffer to byte string */
--    struct inflate_state FAR *state;
--
--    /* check parameters */
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
--
--    /* if first time, start search in bit buffer */
--    if (state->mode != SYNC) {
--        state->mode = SYNC;
--        state->hold <<= state->bits & 7;
--        state->bits -= state->bits & 7;
--        len = 0;
--        while (state->bits >= 8) {
--            buf[len++] = (unsigned char)(state->hold);
--            state->hold >>= 8;
--            state->bits -= 8;
--        }
--        state->have = 0;
--        syncsearch(&(state->have), buf, len);
--    }
--
--    /* search available input */
--    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
--    strm->avail_in -= len;
--    strm->next_in += len;
--    strm->total_in += len;
--
--    /* return no joy or set up to restart inflate() on a new block */
--    if (state->have != 4) return Z_DATA_ERROR;
--    in = strm->total_in;  out = strm->total_out;
--    inflateReset(strm);
--    strm->total_in = in;  strm->total_out = out;
--    state->mode = TYPE;
--    return Z_OK;
--}
--
--/*
--   Returns true if inflate is currently at the end of a block generated by
--   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
--   implementation to provide an additional safety check. PPP uses
--   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
--   block. When decompressing, PPP checks that at the end of input packet,
--   inflate is waiting for these length bytes.
-- */
--int ZEXPORT inflateSyncPoint(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    return state->mode == STORED && state->bits == 0;
--}
--
--int ZEXPORT inflateCopy(dest, source)
--z_streamp dest;
--z_streamp source;
--{
--    struct inflate_state FAR *state;
--    struct inflate_state FAR *copy;
--    unsigned char FAR *window;
--    unsigned wsize;
--
--    /* check input */
--    if (inflateStateCheck(source) || dest == Z_NULL)
--        return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)source->state;
--
--    /* allocate space */
--    copy = (struct inflate_state FAR *)
--           ZALLOC(source, 1, sizeof(struct inflate_state));
--    if (copy == Z_NULL) return Z_MEM_ERROR;
--    window = Z_NULL;
--    if (state->window != Z_NULL) {
--        window = (unsigned char FAR *)
--                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
--        if (window == Z_NULL) {
--            ZFREE(source, copy);
--            return Z_MEM_ERROR;
--        }
--    }
--
--    /* copy state */
--    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
--    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
--    copy->strm = dest;
--    if (state->lencode >= state->codes &&
--        state->lencode <= state->codes + ENOUGH - 1) {
--        copy->lencode = copy->codes + (state->lencode - state->codes);
--        copy->distcode = copy->codes + (state->distcode - state->codes);
--    }
--    copy->next = copy->codes + (state->next - state->codes);
--    if (window != Z_NULL) {
--        wsize = 1U << state->wbits;
--        zmemcpy(window, state->window, wsize);
--    }
--    copy->window = window;
--    dest->state = (struct internal_state FAR *)copy;
--    return Z_OK;
--}
--
--int ZEXPORT inflateUndermine(strm, subvert)
--z_streamp strm;
--int subvert;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
--    state->sane = !subvert;
--    return Z_OK;
--#else
--    (void)subvert;
--    state->sane = 1;
--    return Z_DATA_ERROR;
--#endif
--}
--
--int ZEXPORT inflateValidate(strm, check)
--z_streamp strm;
--int check;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
--    state = (struct inflate_state FAR *)strm->state;
--    if (check)
--        state->wrap |= 4;
--    else
--        state->wrap &= ~4;
--    return Z_OK;
--}
--
--long ZEXPORT inflateMark(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--
--    if (inflateStateCheck(strm))
--        return -(1L << 16);
--    state = (struct inflate_state FAR *)strm->state;
--    return (long)(((unsigned long)((long)state->back)) << 16) +
--        (state->mode == COPY ? state->length :
--            (state->mode == MATCH ? state->was - state->length : 0));
--}
--
--unsigned long ZEXPORT inflateCodesUsed(strm)
--z_streamp strm;
--{
--    struct inflate_state FAR *state;
--    if (inflateStateCheck(strm)) return (unsigned long)-1;
--    state = (struct inflate_state FAR *)strm->state;
--    return (unsigned long)(state->next - state->codes);
--}
diff --cc zlib/inflate.h
index a46cce6b6d05ef994d2a386257cf09068f0aa298,a46cce6b6d05ef994d2a386257cf09068f0aa298..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,125 -1,125 +1,0 @@@
--/* inflate.h -- internal inflate state definition
-- * Copyright (C) 1995-2016 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* WARNING: this file should *not* be used by applications. It is
--   part of the implementation of the compression library and is
--   subject to change. Applications should only use zlib.h.
-- */
--
--/* define NO_GZIP when compiling if you want to disable gzip header and
--   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
--   the crc code when it is not needed.  For shared libraries, gzip decoding
--   should be left enabled. */
--#ifndef NO_GZIP
--#  define GUNZIP
--#endif
--
--/* Possible inflate modes between inflate() calls */
--typedef enum {
--    HEAD = 16180,   /* i: waiting for magic header */
--    FLAGS,      /* i: waiting for method and flags (gzip) */
--    TIME,       /* i: waiting for modification time (gzip) */
--    OS,         /* i: waiting for extra flags and operating system (gzip) */
--    EXLEN,      /* i: waiting for extra length (gzip) */
--    EXTRA,      /* i: waiting for extra bytes (gzip) */
--    NAME,       /* i: waiting for end of file name (gzip) */
--    COMMENT,    /* i: waiting for end of comment (gzip) */
--    HCRC,       /* i: waiting for header crc (gzip) */
--    DICTID,     /* i: waiting for dictionary check value */
--    DICT,       /* waiting for inflateSetDictionary() call */
--        TYPE,       /* i: waiting for type bits, including last-flag bit */
--        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
--        STORED,     /* i: waiting for stored size (length and complement) */
--        COPY_,      /* i/o: same as COPY below, but only first time in */
--        COPY,       /* i/o: waiting for input or output to copy stored block */
--        TABLE,      /* i: waiting for dynamic block table lengths */
--        LENLENS,    /* i: waiting for code length code lengths */
--        CODELENS,   /* i: waiting for length/lit and distance code lengths */
--            LEN_,       /* i: same as LEN below, but only first time in */
--            LEN,        /* i: waiting for length/lit/eob code */
--            LENEXT,     /* i: waiting for length extra bits */
--            DIST,       /* i: waiting for distance code */
--            DISTEXT,    /* i: waiting for distance extra bits */
--            MATCH,      /* o: waiting for output space to copy string */
--            LIT,        /* o: waiting for output space to write literal */
--    CHECK,      /* i: waiting for 32-bit check value */
--    LENGTH,     /* i: waiting for 32-bit length (gzip) */
--    DONE,       /* finished check, done -- remain here until reset */
--    BAD,        /* got a data error -- remain here until reset */
--    MEM,        /* got an inflate() memory error -- remain here until reset */
--    SYNC        /* looking for synchronization bytes to restart inflate() */
--} inflate_mode;
--
--/*
--    State transitions between above modes -
--
--    (most modes can go to BAD or MEM on error -- not shown for clarity)
--
--    Process header:
--        HEAD -> (gzip) or (zlib) or (raw)
--        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
--                  HCRC -> TYPE
--        (zlib) -> DICTID or TYPE
--        DICTID -> DICT -> TYPE
--        (raw) -> TYPEDO
--    Read deflate blocks:
--            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
--            STORED -> COPY_ -> COPY -> TYPE
--            TABLE -> LENLENS -> CODELENS -> LEN_
--            LEN_ -> LEN
--    Read deflate codes in fixed or dynamic block:
--                LEN -> LENEXT or LIT or TYPE
--                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
--                LIT -> LEN
--    Process trailer:
--        CHECK -> LENGTH -> DONE
-- */
--
--/* State maintained between inflate() calls -- approximately 7K bytes, not
--   including the allocated sliding window, which is up to 32K bytes. */
--struct inflate_state {
--    z_streamp strm;             /* pointer back to this zlib stream */
--    inflate_mode mode;          /* current inflate mode */
--    int last;                   /* true if processing last block */
--    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip,
--                                   bit 2 true to validate check value */
--    int havedict;               /* true if dictionary provided */
--    int flags;                  /* gzip header method and flags (0 if zlib) */
--    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
--    unsigned long check;        /* protected copy of check value */
--    unsigned long total;        /* protected copy of output count */
--    gz_headerp head;            /* where to save gzip header information */
--        /* sliding window */
--    unsigned wbits;             /* log base 2 of requested window size */
--    unsigned wsize;             /* window size or zero if not using window */
--    unsigned whave;             /* valid bytes in the window */
--    unsigned wnext;             /* window write index */
--    unsigned char FAR *window;  /* allocated sliding window, if needed */
--        /* bit accumulator */
--    unsigned long hold;         /* input bit accumulator */
--    unsigned bits;              /* number of bits in "in" */
--        /* for string and stored block copying */
--    unsigned length;            /* literal or length of data to copy */
--    unsigned offset;            /* distance back to copy string from */
--        /* for table and code decoding */
--    unsigned extra;             /* extra bits needed */
--        /* fixed and dynamic code tables */
--    code const FAR *lencode;    /* starting table for length/literal codes */
--    code const FAR *distcode;   /* starting table for distance codes */
--    unsigned lenbits;           /* index bits for lencode */
--    unsigned distbits;          /* index bits for distcode */
--        /* dynamic table building */
--    unsigned ncode;             /* number of code length code lengths */
--    unsigned nlen;              /* number of length code lengths */
--    unsigned ndist;             /* number of distance code lengths */
--    unsigned have;              /* number of code lengths in lens[] */
--    code FAR *next;             /* next available space in codes[] */
--    unsigned short lens[320];   /* temporary storage for code lengths */
--    unsigned short work[288];   /* work area for code table building */
--    code codes[ENOUGH];         /* space for code tables */
--    int sane;                   /* if false, allow invalid distance too far */
--    int back;                   /* bits back of last unprocessed length/lit */
--    unsigned was;               /* initial length of match */
--};
diff --cc zlib/inftrees.c
index 2ea08fc13ea8ec50fad1f7574fa287aa6362abc4,2ea08fc13ea8ec50fad1f7574fa287aa6362abc4..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,304 -1,304 +1,0 @@@
--/* inftrees.c -- generate Huffman trees for efficient decoding
-- * Copyright (C) 1995-2017 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--#include "zutil.h"
--#include "inftrees.h"
--
--#define MAXBITS 15
--
--const char inflate_copyright[] =
--   " inflate 1.2.11 Copyright 1995-2017 Mark Adler ";
--/*
--  If you use the zlib library in a product, an acknowledgment is welcome
--  in the documentation of your product. If for some reason you cannot
--  include such an acknowledgment, I would appreciate that you keep this
--  copyright string in the executable of your product.
-- */
--
--/*
--   Build a set of tables to decode the provided canonical Huffman code.
--   The code lengths are lens[0..codes-1].  The result starts at *table,
--   whose indices are 0..2^bits-1.  work is a writable array of at least
--   lens shorts, which is used as a work area.  type is the type of code
--   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
--   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
--   on return points to the next available entry's address.  bits is the
--   requested root table index bits, and on return it is the actual root
--   table index bits.  It will differ if the request is greater than the
--   longest code or if it is less than the shortest code.
-- */
--int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
--codetype type;
--unsigned short FAR *lens;
--unsigned codes;
--code FAR * FAR *table;
--unsigned FAR *bits;
--unsigned short FAR *work;
--{
--    unsigned len;               /* a code's length in bits */
--    unsigned sym;               /* index of code symbols */
--    unsigned min, max;          /* minimum and maximum code lengths */
--    unsigned root;              /* number of index bits for root table */
--    unsigned curr;              /* number of index bits for current table */
--    unsigned drop;              /* code bits to drop for sub-table */
--    int left;                   /* number of prefix codes available */
--    unsigned used;              /* code entries in table used */
--    unsigned huff;              /* Huffman code */
--    unsigned incr;              /* for incrementing code, index */
--    unsigned fill;              /* index for replicating entries */
--    unsigned low;               /* low bits for current root entry */
--    unsigned mask;              /* mask for low root bits */
--    code here;                  /* table entry for duplication */
--    code FAR *next;             /* next available space in table */
--    const unsigned short FAR *base;     /* base value table to use */
--    const unsigned short FAR *extra;    /* extra bits table to use */
--    unsigned match;             /* use base and extra for symbol >= match */
--    unsigned short count[MAXBITS+1];    /* number of codes of each length */
--    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
--    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
--        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
--        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
--    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
--        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
--        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202};
--    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
--        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
--        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
--        8193, 12289, 16385, 24577, 0, 0};
--    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
--        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
--        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
--        28, 28, 29, 29, 64, 64};
--
--    /*
--       Process a set of code lengths to create a canonical Huffman code.  The
--       code lengths are lens[0..codes-1].  Each length corresponds to the
--       symbols 0..codes-1.  The Huffman code is generated by first sorting the
--       symbols by length from short to long, and retaining the symbol order
--       for codes with equal lengths.  Then the code starts with all zero bits
--       for the first code of the shortest length, and the codes are integer
--       increments for the same length, and zeros are appended as the length
--       increases.  For the deflate format, these bits are stored backwards
--       from their more natural integer increment ordering, and so when the
--       decoding tables are built in the large loop below, the integer codes
--       are incremented backwards.
--
--       This routine assumes, but does not check, that all of the entries in
--       lens[] are in the range 0..MAXBITS.  The caller must assure this.
--       1..MAXBITS is interpreted as that code length.  zero means that that
--       symbol does not occur in this code.
--
--       The codes are sorted by computing a count of codes for each length,
--       creating from that a table of starting indices for each length in the
--       sorted table, and then entering the symbols in order in the sorted
--       table.  The sorted table is work[], with that space being provided by
--       the caller.
--
--       The length counts are used for other purposes as well, i.e. finding
--       the minimum and maximum length codes, determining if there are any
--       codes at all, checking for a valid set of lengths, and looking ahead
--       at length counts to determine sub-table sizes when building the
--       decoding tables.
--     */
--
--    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
--    for (len = 0; len <= MAXBITS; len++)
--        count[len] = 0;
--    for (sym = 0; sym < codes; sym++)
--        count[lens[sym]]++;
--
--    /* bound code lengths, force root to be within code lengths */
--    root = *bits;
--    for (max = MAXBITS; max >= 1; max--)
--        if (count[max] != 0) break;
--    if (root > max) root = max;
--    if (max == 0) {                     /* no symbols to code at all */
--        here.op = (unsigned char)64;    /* invalid code marker */
--        here.bits = (unsigned char)1;
--        here.val = (unsigned short)0;
--        *(*table)++ = here;             /* make a table to force an error */
--        *(*table)++ = here;
--        *bits = 1;
--        return 0;     /* no symbols, but wait for decoding to report error */
--    }
--    for (min = 1; min < max; min++)
--        if (count[min] != 0) break;
--    if (root < min) root = min;
--
--    /* check for an over-subscribed or incomplete set of lengths */
--    left = 1;
--    for (len = 1; len <= MAXBITS; len++) {
--        left <<= 1;
--        left -= count[len];
--        if (left < 0) return -1;        /* over-subscribed */
--    }
--    if (left > 0 && (type == CODES || max != 1))
--        return -1;                      /* incomplete set */
--
--    /* generate offsets into symbol table for each length for sorting */
--    offs[1] = 0;
--    for (len = 1; len < MAXBITS; len++)
--        offs[len + 1] = offs[len] + count[len];
--
--    /* sort symbols by length, by symbol order within each length */
--    for (sym = 0; sym < codes; sym++)
--        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
--
--    /*
--       Create and fill in decoding tables.  In this loop, the table being
--       filled is at next and has curr index bits.  The code being used is huff
--       with length len.  That code is converted to an index by dropping drop
--       bits off of the bottom.  For codes where len is less than drop + curr,
--       those top drop + curr - len bits are incremented through all values to
--       fill the table with replicated entries.
--
--       root is the number of index bits for the root table.  When len exceeds
--       root, sub-tables are created pointed to by the root entry with an index
--       of the low root bits of huff.  This is saved in low to check for when a
--       new sub-table should be started.  drop is zero when the root table is
--       being filled, and drop is root when sub-tables are being filled.
--
--       When a new sub-table is needed, it is necessary to look ahead in the
--       code lengths to determine what size sub-table is needed.  The length
--       counts are used for this, and so count[] is decremented as codes are
--       entered in the tables.
--
--       used keeps track of how many table entries have been allocated from the
--       provided *table space.  It is checked for LENS and DIST tables against
--       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
--       the initial root table size constants.  See the comments in inftrees.h
--       for more information.
--
--       sym increments through all symbols, and the loop terminates when
--       all codes of length max, i.e. all codes, have been processed.  This
--       routine permits incomplete codes, so another loop after this one fills
--       in the rest of the decoding tables with invalid code markers.
--     */
--
--    /* set up for code type */
--    switch (type) {
--    case CODES:
--        base = extra = work;    /* dummy value--not used */
--        match = 20;
--        break;
--    case LENS:
--        base = lbase;
--        extra = lext;
--        match = 257;
--        break;
--    default:    /* DISTS */
--        base = dbase;
--        extra = dext;
--        match = 0;
--    }
--
--    /* initialize state for loop */
--    huff = 0;                   /* starting code */
--    sym = 0;                    /* starting code symbol */
--    len = min;                  /* starting code length */
--    next = *table;              /* current table to fill in */
--    curr = root;                /* current table index bits */
--    drop = 0;                   /* current bits to drop from code for index */
--    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
--    used = 1U << root;          /* use root table entries */
--    mask = used - 1;            /* mask for comparing low */
--
--    /* check available table space */
--    if ((type == LENS && used > ENOUGH_LENS) ||
--        (type == DISTS && used > ENOUGH_DISTS))
--        return 1;
--
--    /* process all codes and make table entries */
--    for (;;) {
--        /* create table entry */
--        here.bits = (unsigned char)(len - drop);
--        if (work[sym] + 1U < match) {
--            here.op = (unsigned char)0;
--            here.val = work[sym];
--        }
--        else if (work[sym] >= match) {
--            here.op = (unsigned char)(extra[work[sym] - match]);
--            here.val = base[work[sym] - match];
--        }
--        else {
--            here.op = (unsigned char)(32 + 64);         /* end of block */
--            here.val = 0;
--        }
--
--        /* replicate for those indices with low len bits equal to huff */
--        incr = 1U << (len - drop);
--        fill = 1U << curr;
--        min = fill;                 /* save offset to next table */
--        do {
--            fill -= incr;
--            next[(huff >> drop) + fill] = here;
--        } while (fill != 0);
--
--        /* backwards increment the len-bit code huff */
--        incr = 1U << (len - 1);
--        while (huff & incr)
--            incr >>= 1;
--        if (incr != 0) {
--            huff &= incr - 1;
--            huff += incr;
--        }
--        else
--            huff = 0;
--
--        /* go to next symbol, update count, len */
--        sym++;
--        if (--(count[len]) == 0) {
--            if (len == max) break;
--            len = lens[work[sym]];
--        }
--
--        /* create new sub-table if needed */
--        if (len > root && (huff & mask) != low) {
--            /* if first time, transition to sub-tables */
--            if (drop == 0)
--                drop = root;
--
--            /* increment past last table */
--            next += min;            /* here min is 1 << curr */
--
--            /* determine length of next table */
--            curr = len - drop;
--            left = (int)(1 << curr);
--            while (curr + drop < max) {
--                left -= count[curr + drop];
--                if (left <= 0) break;
--                curr++;
--                left <<= 1;
--            }
--
--            /* check for enough space */
--            used += 1U << curr;
--            if ((type == LENS && used > ENOUGH_LENS) ||
--                (type == DISTS && used > ENOUGH_DISTS))
--                return 1;
--
--            /* point entry in root table to sub-table */
--            low = huff & mask;
--            (*table)[low].op = (unsigned char)curr;
--            (*table)[low].bits = (unsigned char)root;
--            (*table)[low].val = (unsigned short)(next - *table);
--        }
--    }
--
--    /* fill in remaining table entry if code is incomplete (guaranteed to have
--       at most one remaining entry, since if the code is incomplete, the
--       maximum code length that was allowed to get this far is one bit) */
--    if (huff != 0) {
--        here.op = (unsigned char)64;            /* invalid code marker */
--        here.bits = (unsigned char)(len - drop);
--        here.val = (unsigned short)0;
--        next[huff] = here;
--    }
--
--    /* set return parameters */
--    *table += used;
--    *bits = root;
--    return 0;
--}
diff --cc zlib/inftrees.h
index baa53a0b1a199ce6ea4c3f99d0306502ab4fab2c,baa53a0b1a199ce6ea4c3f99d0306502ab4fab2c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,62 -1,62 +1,0 @@@
--/* inftrees.h -- header to use inftrees.c
-- * Copyright (C) 1995-2005, 2010 Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* WARNING: this file should *not* be used by applications. It is
--   part of the implementation of the compression library and is
--   subject to change. Applications should only use zlib.h.
-- */
--
--/* Structure for decoding tables.  Each entry provides either the
--   information needed to do the operation requested by the code that
--   indexed that table entry, or it provides a pointer to another
--   table that indexes more bits of the code.  op indicates whether
--   the entry is a pointer to another table, a literal, a length or
--   distance, an end-of-block, or an invalid code.  For a table
--   pointer, the low four bits of op is the number of index bits of
--   that table.  For a length or distance, the low four bits of op
--   is the number of extra bits to get after the code.  bits is
--   the number of bits in this code or part of the code to drop off
--   of the bit buffer.  val is the actual byte to output in the case
--   of a literal, the base length or distance, or the offset from
--   the current table to the next table.  Each entry is four bytes. */
--typedef struct {
--    unsigned char op;           /* operation, extra bits, table bits */
--    unsigned char bits;         /* bits in this part of the code */
--    unsigned short val;         /* offset in table or code value */
--} code;
--
--/* op values as set by inflate_table():
--    00000000 - literal
--    0000tttt - table link, tttt != 0 is the number of table index bits
--    0001eeee - length or distance, eeee is the number of extra bits
--    01100000 - end of block
--    01000000 - invalid code
-- */
--
--/* Maximum size of the dynamic table.  The maximum number of code structures is
--   1444, which is the sum of 852 for literal/length codes and 592 for distance
--   codes.  These values were found by exhaustive searches using the program
--   examples/enough.c found in the zlib distribtution.  The arguments to that
--   program are the number of symbols, the initial root table size, and the
--   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
--   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
--   The initial root table size (9 or 6) is found in the fifth argument of the
--   inflate_table() calls in inflate.c and infback.c.  If the root table size is
--   changed, then these maximum sizes would be need to be recalculated and
--   updated. */
--#define ENOUGH_LENS 852
--#define ENOUGH_DISTS 592
--#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
--
--/* Type of code to build for inflate_table() */
--typedef enum {
--    CODES,
--    LENS,
--    DISTS
--} codetype;
--
--int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
--                             unsigned codes, code FAR * FAR *table,
--                             unsigned FAR *bits, unsigned short FAR *work));
diff --cc zlib/resync_zlib
index 44c37ac36c20367528469983b7c352ef912b15aa,44c37ac36c20367528469983b7c352ef912b15aa..0000000000000000000000000000000000000000
deleted file mode 100755,100755
+++ /dev/null
@@@ -1,134 -1,134 +1,0 @@@
--#!/bin/bash -ex
--# This is a historical record of how we did the merge between our
--# fork of glib 1.2.8 and the vendor update to 1.2.11
--# It may be of use when we sync up with a future vendor update.
--# It should not be expected to work without being modified!
--rm -fr zlib
--rm -fr zlib.old
--rm -fr zlib.new
--git checkout -- zlib
--# I manually found all the files we modified after the zlib
--# 1.2.8 release with "diff -r".
--# I then did three way compares between zlib 1.2.8, our code,
--# and zlib 1.2.11.
--# We had modified 7 files.  For the 5 below I wanted to preserve
--# our changes so I generate patches to apply to zlib 1.2.11.
--# The other 2 were gzlib.c and inflate.c.
--# In the case of gzlib.c we had a patch to fix a seek issue.
--# This was reported to the zlib creators with a test case.
--# 1.2.11 did not incorporate our patch, but the issue was fixed
--# in another manner.  Therfore we accept 1.2.11 gzlib.c without
--# our changes.
--# Both the test case we submitted to zlib and our gpsbabel
--# testcase were recreated to verify the failure in 1.2.8 and
--# verify that it was fixed in 1.2.11.
--# The last case was inflate.c.  In that case both zlib 1.2.11
--# and ourselves had the same change.  Therefore we accept 1.2.11
--# inflate.c without our changes.
--#
--# generate patches between 1.2.8 and our current zlib
--diff -u ../zlib-1.2.8/contrib/minizip/ioapi.c zlib/contrib/minizip 1> ioapi.c.patch || true
--diff -u ../zlib-1.2.8/contrib/minizip/ioapi.h zlib/contrib/minizip 1> ioapi.h.patch || true
--diff -u ../zlib-1.2.8/contrib/minizip/zip.c zlib/contrib/minizip 1> zip.c.patch || true
--diff -u ../zlib-1.2.8/contrib/minizip/zip.h zlib/contrib/minizip 1> zip.h.patch || true
--diff -u ../zlib-1.2.8/zconf.h zlib 1> zconf.h.patch || true
--
--mv zlib zlib.old
--
--tar -xzvf ../../Downloads/zlib-1.2.11.tar.gz
--mv zlib-1.2.11 zlib
--cd zlib
--
--mv doc/algorithm.txt .
--
--rm -fr amiga
--rm -fr doc
--rm -fr examples
--rm -fr msdos
--rm -fr nintendods
--rm -fr old
--rm -fr os400
--rm -fr qnx
--rm -fr test
--rm -fr watcom
--rm -fr win32
--rm -f configure
--rm -f CMakeLists.txt
--rm -f INDEX
--rm -f Makefile
--rm -f make_vms.com
--rm -f treebuild.xml
--rm -f zlib2ansi
--rm -f zconf.h.cmakein
--rm -f zlib.3.pdf
--rm -f zlib.map
--rm -f zlib.pc.cmakein
--rm -f zlib.pc.in
--rm -fr contrib/ada
--rm -fr contrib/amd64
--rm -fr contrib/asm686
--rm -fr contrib/blast
--rm -fr contrib/delphi
--rm -fr contrib/dotzlib
--rm -fr contrib/gcc_gvmat64
--rm -fr contrib/infback9
--rm -fr contrib/inflate86
--rm -fr contrib/iostream
--rm -fr contrib/iostream2
--rm -fr contrib/iostream3
--rm -fr contrib/masmx64
--rm -fr contrib/masmx86
--rm -fr contrib/pascal
--rm -fr contrib/puff
--rm -fr contrib/README.contrib
--rm -fr contrib/testzlib
--rm -fr contrib/untgz
--rm -fr contrib/vstudio
--# rename .in files to protect them from auto tools.
--mv zconf.h.in  zconf.in.h
--mv -f Makefile.in Makefile.in.zlib
--
--# copy our unique files
--cp -p ../zlib.old/README.gpsbabel .
--cp -p ../zlib.old/.gitignore .
--cp -p ../zlib.old/empty.in .
--
--# we don't neet this anymore, but it makes the diff line up
--# it will be deleted below.
--cp -p ../zlib.old/gzlib.patch .
--cd ..
--find zlib | sort > zlib.new.list
--find zlib.old | sort > zlib.old.list
--
--# move patches
--mv ioapi.c.patch zlib/contrib/minizip
--mv ioapi.h.patch zlib/contrib/minizip
--mv zip.c.patch zlib/contrib/minizip
--mv zip.h.patch zlib/contrib/minizip
--mv zconf.h.patch zlib
--
--# apply patches
--cd zlib/contrib/minizip
--patch < ioapi.c.patch
--patch < ioapi.h.patch
--patch < zip.c.patch
--patch < zip.h.patch
--cd ../..
--patch < zconf.h.patch
--
--cd ..
--cp resync_zlib zlib
--
--echo "see $0 for git commands to run manually"
--# this patch is obsolete
--#git rm zlib/gzlib.patch
--# and these are new files
--#git add zlib/contrib/minizip/ioapi.c.patch
--#git add zlib/contrib/minizip/ioapi.h.patch
--#git add zlib/contrib/minizip/zip.c.patch
--#git add zlib/contrib/minizip/zip.h.patch
--#git add zlib/zconf.h.patch
--#git add zlib/resync_zlib
--
--echo "you must manually edit README.gpsbabel"
--echo "Done"
diff --cc zlib/trees.c
index 50cf4b4571cfec347ce5891b76fcb6675fcb580d,50cf4b4571cfec347ce5891b76fcb6675fcb580d..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1203 -1,1203 +1,0 @@@
--/* trees.c -- output deflated data using Huffman coding
-- * Copyright (C) 1995-2017 Jean-loup Gailly
-- * detect_data_type() function provided freely by Cosmin Truta, 2006
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/*
-- *  ALGORITHM
-- *
-- *      The "deflation" process uses several Huffman trees. The more
-- *      common source values are represented by shorter bit sequences.
-- *
-- *      Each code tree is stored in a compressed form which is itself
-- * a Huffman encoding of the lengths of all the code strings (in
-- * ascending order by source values).  The actual code strings are
-- * reconstructed from the lengths in the inflate process, as described
-- * in the deflate specification.
-- *
-- *  REFERENCES
-- *
-- *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
-- *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
-- *
-- *      Storer, James A.
-- *          Data Compression:  Methods and Theory, pp. 49-50.
-- *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
-- *
-- *      Sedgewick, R.
-- *          Algorithms, p290.
-- *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
-- */
--
--/* @(#) $Id$ */
--
--/* #define GEN_TREES_H */
--
--#include "deflate.h"
--
--#ifdef ZLIB_DEBUG
--#  include <ctype.h>
--#endif
--
--/* ===========================================================================
-- * Constants
-- */
--
--#define MAX_BL_BITS 7
--/* Bit length codes must not exceed MAX_BL_BITS bits */
--
--#define END_BLOCK 256
--/* end of block literal code */
--
--#define REP_3_6      16
--/* repeat previous bit length 3-6 times (2 bits of repeat count) */
--
--#define REPZ_3_10    17
--/* repeat a zero length 3-10 times  (3 bits of repeat count) */
--
--#define REPZ_11_138  18
--/* repeat a zero length 11-138 times  (7 bits of repeat count) */
--
--local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
--   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
--
--local const int extra_dbits[D_CODES] /* extra bits for each distance code */
--   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
--
--local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
--   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
--
--local const uch bl_order[BL_CODES]
--   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
--/* The lengths of the bit length codes are sent in order of decreasing
-- * probability, to avoid transmitting the lengths for unused bit length codes.
-- */
--
--/* ===========================================================================
-- * Local data. These are initialized only once.
-- */
--
--#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
--
--#if defined(GEN_TREES_H) || !defined(STDC)
--/* non ANSI compilers may not accept trees.h */
--
--local ct_data static_ltree[L_CODES+2];
--/* The static literal tree. Since the bit lengths are imposed, there is no
-- * need for the L_CODES extra codes used during heap construction. However
-- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
-- * below).
-- */
--
--local ct_data static_dtree[D_CODES];
--/* The static distance tree. (Actually a trivial tree since all codes use
-- * 5 bits.)
-- */
--
--uch _dist_code[DIST_CODE_LEN];
--/* Distance codes. The first 256 values correspond to the distances
-- * 3 .. 258, the last 256 values correspond to the top 8 bits of
-- * the 15 bit distances.
-- */
--
--uch _length_code[MAX_MATCH-MIN_MATCH+1];
--/* length code for each normalized match length (0 == MIN_MATCH) */
--
--local int base_length[LENGTH_CODES];
--/* First normalized length for each code (0 = MIN_MATCH) */
--
--local int base_dist[D_CODES];
--/* First normalized distance for each code (0 = distance of 1) */
--
--#else
--#  include "trees.h"
--#endif /* GEN_TREES_H */
--
--struct static_tree_desc_s {
--    const ct_data *static_tree;  /* static tree or NULL */
--    const intf *extra_bits;      /* extra bits for each code or NULL */
--    int     extra_base;          /* base index for extra_bits */
--    int     elems;               /* max number of elements in the tree */
--    int     max_length;          /* max bit length for the codes */
--};
--
--local const static_tree_desc  static_l_desc =
--{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
--
--local const static_tree_desc  static_d_desc =
--{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
--
--local const static_tree_desc  static_bl_desc =
--{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
--
--/* ===========================================================================
-- * Local (static) routines in this file.
-- */
--
--local void tr_static_init OF((void));
--local void init_block     OF((deflate_state *s));
--local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
--local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
--local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
--local void build_tree     OF((deflate_state *s, tree_desc *desc));
--local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
--local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
--local int  build_bl_tree  OF((deflate_state *s));
--local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
--                              int blcodes));
--local void compress_block OF((deflate_state *s, const ct_data *ltree,
--                              const ct_data *dtree));
--local int  detect_data_type OF((deflate_state *s));
--local unsigned bi_reverse OF((unsigned value, int length));
--local void bi_windup      OF((deflate_state *s));
--local void bi_flush       OF((deflate_state *s));
--
--#ifdef GEN_TREES_H
--local void gen_trees_header OF((void));
--#endif
--
--#ifndef ZLIB_DEBUG
--#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
--   /* Send a code of the given tree. c and tree must not have side effects */
--
--#else /* !ZLIB_DEBUG */
--#  define send_code(s, c, tree) \
--     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
--       send_bits(s, tree[c].Code, tree[c].Len); }
--#endif
--
--/* ===========================================================================
-- * Output a short LSB first on the stream.
-- * IN assertion: there is enough room in pendingBuf.
-- */
--#define put_short(s, w) { \
--    put_byte(s, (uch)((w) & 0xff)); \
--    put_byte(s, (uch)((ush)(w) >> 8)); \
--}
--
--/* ===========================================================================
-- * Send a value on a given number of bits.
-- * IN assertion: length <= 16 and value fits in length bits.
-- */
--#ifdef ZLIB_DEBUG
--local void send_bits      OF((deflate_state *s, int value, int length));
--
--local void send_bits(s, value, length)
--    deflate_state *s;
--    int value;  /* value to send */
--    int length; /* number of bits */
--{
--    Tracevv((stderr," l %2d v %4x ", length, value));
--    Assert(length > 0 && length <= 15, "invalid length");
--    s->bits_sent += (ulg)length;
--
--    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
--     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
--     * unused bits in value.
--     */
--    if (s->bi_valid > (int)Buf_size - length) {
--        s->bi_buf |= (ush)value << s->bi_valid;
--        put_short(s, s->bi_buf);
--        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
--        s->bi_valid += length - Buf_size;
--    } else {
--        s->bi_buf |= (ush)value << s->bi_valid;
--        s->bi_valid += length;
--    }
--}
--#else /* !ZLIB_DEBUG */
--
--#define send_bits(s, value, length) \
--{ int len = length;\
--  if (s->bi_valid > (int)Buf_size - len) {\
--    int val = (int)value;\
--    s->bi_buf |= (ush)val << s->bi_valid;\
--    put_short(s, s->bi_buf);\
--    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
--    s->bi_valid += len - Buf_size;\
--  } else {\
--    s->bi_buf |= (ush)(value) << s->bi_valid;\
--    s->bi_valid += len;\
--  }\
--}
--#endif /* ZLIB_DEBUG */
--
--
--/* the arguments must not have side effects */
--
--/* ===========================================================================
-- * Initialize the various 'constant' tables.
-- */
--local void tr_static_init()
--{
--#if defined(GEN_TREES_H) || !defined(STDC)
--    static int static_init_done = 0;
--    int n;        /* iterates over tree elements */
--    int bits;     /* bit counter */
--    int length;   /* length value */
--    int code;     /* code value */
--    int dist;     /* distance index */
--    ush bl_count[MAX_BITS+1];
--    /* number of codes at each bit length for an optimal tree */
--
--    if (static_init_done) return;
--
--    /* For some embedded targets, global variables are not initialized: */
--#ifdef NO_INIT_GLOBAL_POINTERS
--    static_l_desc.static_tree = static_ltree;
--    static_l_desc.extra_bits = extra_lbits;
--    static_d_desc.static_tree = static_dtree;
--    static_d_desc.extra_bits = extra_dbits;
--    static_bl_desc.extra_bits = extra_blbits;
--#endif
--
--    /* Initialize the mapping length (0..255) -> length code (0..28) */
--    length = 0;
--    for (code = 0; code < LENGTH_CODES-1; code++) {
--        base_length[code] = length;
--        for (n = 0; n < (1<<extra_lbits[code]); n++) {
--            _length_code[length++] = (uch)code;
--        }
--    }
--    Assert (length == 256, "tr_static_init: length != 256");
--    /* Note that the length 255 (match length 258) can be represented
--     * in two different ways: code 284 + 5 bits or code 285, so we
--     * overwrite length_code[255] to use the best encoding:
--     */
--    _length_code[length-1] = (uch)code;
--
--    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
--    dist = 0;
--    for (code = 0 ; code < 16; code++) {
--        base_dist[code] = dist;
--        for (n = 0; n < (1<<extra_dbits[code]); n++) {
--            _dist_code[dist++] = (uch)code;
--        }
--    }
--    Assert (dist == 256, "tr_static_init: dist != 256");
--    dist >>= 7; /* from now on, all distances are divided by 128 */
--    for ( ; code < D_CODES; code++) {
--        base_dist[code] = dist << 7;
--        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
--            _dist_code[256 + dist++] = (uch)code;
--        }
--    }
--    Assert (dist == 256, "tr_static_init: 256+dist != 512");
--
--    /* Construct the codes of the static literal tree */
--    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
--    n = 0;
--    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
--    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
--    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
--    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
--    /* Codes 286 and 287 do not exist, but we must include them in the
--     * tree construction to get a canonical Huffman tree (longest code
--     * all ones)
--     */
--    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
--
--    /* The static distance tree is trivial: */
--    for (n = 0; n < D_CODES; n++) {
--        static_dtree[n].Len = 5;
--        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
--    }
--    static_init_done = 1;
--
--#  ifdef GEN_TREES_H
--    gen_trees_header();
--#  endif
--#endif /* defined(GEN_TREES_H) || !defined(STDC) */
--}
--
--/* ===========================================================================
-- * Genererate the file trees.h describing the static trees.
-- */
--#ifdef GEN_TREES_H
--#  ifndef ZLIB_DEBUG
--#    include <stdio.h>
--#  endif
--
--#  define SEPARATOR(i, last, width) \
--      ((i) == (last)? "\n};\n\n" :    \
--       ((i) % (width) == (width)-1 ? ",\n" : ", "))
--
--void gen_trees_header()
--{
--    FILE *header = fopen("trees.h", "w");
--    int i;
--
--    Assert (header != NULL, "Can't open trees.h");
--    fprintf(header,
--            "/* header created automatically with -DGEN_TREES_H */\n\n");
--
--    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
--    for (i = 0; i < L_CODES+2; i++) {
--        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
--                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
--    }
--
--    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
--    for (i = 0; i < D_CODES; i++) {
--        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
--                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
--    }
--
--    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
--    for (i = 0; i < DIST_CODE_LEN; i++) {
--        fprintf(header, "%2u%s", _dist_code[i],
--                SEPARATOR(i, DIST_CODE_LEN-1, 20));
--    }
--
--    fprintf(header,
--        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
--    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
--        fprintf(header, "%2u%s", _length_code[i],
--                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
--    }
--
--    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
--    for (i = 0; i < LENGTH_CODES; i++) {
--        fprintf(header, "%1u%s", base_length[i],
--                SEPARATOR(i, LENGTH_CODES-1, 20));
--    }
--
--    fprintf(header, "local const int base_dist[D_CODES] = {\n");
--    for (i = 0; i < D_CODES; i++) {
--        fprintf(header, "%5u%s", base_dist[i],
--                SEPARATOR(i, D_CODES-1, 10));
--    }
--
--    fclose(header);
--}
--#endif /* GEN_TREES_H */
--
--/* ===========================================================================
-- * Initialize the tree data structures for a new zlib stream.
-- */
--void ZLIB_INTERNAL _tr_init(s)
--    deflate_state *s;
--{
--    tr_static_init();
--
--    s->l_desc.dyn_tree = s->dyn_ltree;
--    s->l_desc.stat_desc = &static_l_desc;
--
--    s->d_desc.dyn_tree = s->dyn_dtree;
--    s->d_desc.stat_desc = &static_d_desc;
--
--    s->bl_desc.dyn_tree = s->bl_tree;
--    s->bl_desc.stat_desc = &static_bl_desc;
--
--    s->bi_buf = 0;
--    s->bi_valid = 0;
--#ifdef ZLIB_DEBUG
--    s->compressed_len = 0L;
--    s->bits_sent = 0L;
--#endif
--
--    /* Initialize the first block of the first file: */
--    init_block(s);
--}
--
--/* ===========================================================================
-- * Initialize a new block.
-- */
--local void init_block(s)
--    deflate_state *s;
--{
--    int n; /* iterates over tree elements */
--
--    /* Initialize the trees. */
--    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
--    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
--    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
--
--    s->dyn_ltree[END_BLOCK].Freq = 1;
--    s->opt_len = s->static_len = 0L;
--    s->last_lit = s->matches = 0;
--}
--
--#define SMALLEST 1
--/* Index within the heap array of least frequent node in the Huffman tree */
--
--
--/* ===========================================================================
-- * Remove the smallest element from the heap and recreate the heap with
-- * one less element. Updates heap and heap_len.
-- */
--#define pqremove(s, tree, top) \
--{\
--    top = s->heap[SMALLEST]; \
--    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
--    pqdownheap(s, tree, SMALLEST); \
--}
--
--/* ===========================================================================
-- * Compares to subtrees, using the tree depth as tie breaker when
-- * the subtrees have equal frequency. This minimizes the worst case length.
-- */
--#define smaller(tree, n, m, depth) \
--   (tree[n].Freq < tree[m].Freq || \
--   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
--
--/* ===========================================================================
-- * Restore the heap property by moving down the tree starting at node k,
-- * exchanging a node with the smallest of its two sons if necessary, stopping
-- * when the heap property is re-established (each father smaller than its
-- * two sons).
-- */
--local void pqdownheap(s, tree, k)
--    deflate_state *s;
--    ct_data *tree;  /* the tree to restore */
--    int k;               /* node to move down */
--{
--    int v = s->heap[k];
--    int j = k << 1;  /* left son of k */
--    while (j <= s->heap_len) {
--        /* Set j to the smallest of the two sons: */
--        if (j < s->heap_len &&
--            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
--            j++;
--        }
--        /* Exit if v is smaller than both sons */
--        if (smaller(tree, v, s->heap[j], s->depth)) break;
--
--        /* Exchange v with the smallest son */
--        s->heap[k] = s->heap[j];  k = j;
--
--        /* And continue down the tree, setting j to the left son of k */
--        j <<= 1;
--    }
--    s->heap[k] = v;
--}
--
--/* ===========================================================================
-- * Compute the optimal bit lengths for a tree and update the total bit length
-- * for the current block.
-- * IN assertion: the fields freq and dad are set, heap[heap_max] and
-- *    above are the tree nodes sorted by increasing frequency.
-- * OUT assertions: the field len is set to the optimal bit length, the
-- *     array bl_count contains the frequencies for each bit length.
-- *     The length opt_len is updated; static_len is also updated if stree is
-- *     not null.
-- */
--local void gen_bitlen(s, desc)
--    deflate_state *s;
--    tree_desc *desc;    /* the tree descriptor */
--{
--    ct_data *tree        = desc->dyn_tree;
--    int max_code         = desc->max_code;
--    const ct_data *stree = desc->stat_desc->static_tree;
--    const intf *extra    = desc->stat_desc->extra_bits;
--    int base             = desc->stat_desc->extra_base;
--    int max_length       = desc->stat_desc->max_length;
--    int h;              /* heap index */
--    int n, m;           /* iterate over the tree elements */
--    int bits;           /* bit length */
--    int xbits;          /* extra bits */
--    ush f;              /* frequency */
--    int overflow = 0;   /* number of elements with bit length too large */
--
--    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
--
--    /* In a first pass, compute the optimal bit lengths (which may
--     * overflow in the case of the bit length tree).
--     */
--    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
--
--    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
--        n = s->heap[h];
--        bits = tree[tree[n].Dad].Len + 1;
--        if (bits > max_length) bits = max_length, overflow++;
--        tree[n].Len = (ush)bits;
--        /* We overwrite tree[n].Dad which is no longer needed */
--
--        if (n > max_code) continue; /* not a leaf node */
--
--        s->bl_count[bits]++;
--        xbits = 0;
--        if (n >= base) xbits = extra[n-base];
--        f = tree[n].Freq;
--        s->opt_len += (ulg)f * (unsigned)(bits + xbits);
--        if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
--    }
--    if (overflow == 0) return;
--
--    Tracev((stderr,"\nbit length overflow\n"));
--    /* This happens for example on obj2 and pic of the Calgary corpus */
--
--    /* Find the first bit length which could increase: */
--    do {
--        bits = max_length-1;
--        while (s->bl_count[bits] == 0) bits--;
--        s->bl_count[bits]--;      /* move one leaf down the tree */
--        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
--        s->bl_count[max_length]--;
--        /* The brother of the overflow item also moves one step up,
--         * but this does not affect bl_count[max_length]
--         */
--        overflow -= 2;
--    } while (overflow > 0);
--
--    /* Now recompute all bit lengths, scanning in increasing frequency.
--     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
--     * lengths instead of fixing only the wrong ones. This idea is taken
--     * from 'ar' written by Haruhiko Okumura.)
--     */
--    for (bits = max_length; bits != 0; bits--) {
--        n = s->bl_count[bits];
--        while (n != 0) {
--            m = s->heap[--h];
--            if (m > max_code) continue;
--            if ((unsigned) tree[m].Len != (unsigned) bits) {
--                Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
--                s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
--                tree[m].Len = (ush)bits;
--            }
--            n--;
--        }
--    }
--}
--
--/* ===========================================================================
-- * Generate the codes for a given tree and bit counts (which need not be
-- * optimal).
-- * IN assertion: the array bl_count contains the bit length statistics for
-- * the given tree and the field len is set for all tree elements.
-- * OUT assertion: the field code is set for all tree elements of non
-- *     zero code length.
-- */
--local void gen_codes (tree, max_code, bl_count)
--    ct_data *tree;             /* the tree to decorate */
--    int max_code;              /* largest code with non zero frequency */
--    ushf *bl_count;            /* number of codes at each bit length */
--{
--    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
--    unsigned code = 0;         /* running code value */
--    int bits;                  /* bit index */
--    int n;                     /* code index */
--
--    /* The distribution counts are first used to generate the code values
--     * without bit reversal.
--     */
--    for (bits = 1; bits <= MAX_BITS; bits++) {
--        code = (code + bl_count[bits-1]) << 1;
--        next_code[bits] = (ush)code;
--    }
--    /* Check that the bit counts in bl_count are consistent. The last code
--     * must be all ones.
--     */
--    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
--            "inconsistent bit counts");
--    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
--
--    for (n = 0;  n <= max_code; n++) {
--        int len = tree[n].Len;
--        if (len == 0) continue;
--        /* Now reverse the bits */
--        tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
--
--        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
--             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
--    }
--}
--
--/* ===========================================================================
-- * Construct one Huffman tree and assigns the code bit strings and lengths.
-- * Update the total bit length for the current block.
-- * IN assertion: the field freq is set for all tree elements.
-- * OUT assertions: the fields len and code are set to the optimal bit length
-- *     and corresponding code. The length opt_len is updated; static_len is
-- *     also updated if stree is not null. The field max_code is set.
-- */
--local void build_tree(s, desc)
--    deflate_state *s;
--    tree_desc *desc; /* the tree descriptor */
--{
--    ct_data *tree         = desc->dyn_tree;
--    const ct_data *stree  = desc->stat_desc->static_tree;
--    int elems             = desc->stat_desc->elems;
--    int n, m;          /* iterate over heap elements */
--    int max_code = -1; /* largest code with non zero frequency */
--    int node;          /* new node being created */
--
--    /* Construct the initial heap, with least frequent element in
--     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
--     * heap[0] is not used.
--     */
--    s->heap_len = 0, s->heap_max = HEAP_SIZE;
--
--    for (n = 0; n < elems; n++) {
--        if (tree[n].Freq != 0) {
--            s->heap[++(s->heap_len)] = max_code = n;
--            s->depth[n] = 0;
--        } else {
--            tree[n].Len = 0;
--        }
--    }
--
--    /* The pkzip format requires that at least one distance code exists,
--     * and that at least one bit should be sent even if there is only one
--     * possible code. So to avoid special checks later on we force at least
--     * two codes of non zero frequency.
--     */
--    while (s->heap_len < 2) {
--        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
--        tree[node].Freq = 1;
--        s->depth[node] = 0;
--        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
--        /* node is 0 or 1 so it does not have extra bits */
--    }
--    desc->max_code = max_code;
--
--    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
--     * establish sub-heaps of increasing lengths:
--     */
--    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
--
--    /* Construct the Huffman tree by repeatedly combining the least two
--     * frequent nodes.
--     */
--    node = elems;              /* next internal node of the tree */
--    do {
--        pqremove(s, tree, n);  /* n = node of least frequency */
--        m = s->heap[SMALLEST]; /* m = node of next least frequency */
--
--        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
--        s->heap[--(s->heap_max)] = m;
--
--        /* Create a new node father of n and m */
--        tree[node].Freq = tree[n].Freq + tree[m].Freq;
--        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
--                                s->depth[n] : s->depth[m]) + 1);
--        tree[n].Dad = tree[m].Dad = (ush)node;
--#ifdef DUMP_BL_TREE
--        if (tree == s->bl_tree) {
--            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
--                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
--        }
--#endif
--        /* and insert the new node in the heap */
--        s->heap[SMALLEST] = node++;
--        pqdownheap(s, tree, SMALLEST);
--
--    } while (s->heap_len >= 2);
--
--    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
--
--    /* At this point, the fields freq and dad are set. We can now
--     * generate the bit lengths.
--     */
--    gen_bitlen(s, (tree_desc *)desc);
--
--    /* The field len is now set, we can generate the bit codes */
--    gen_codes ((ct_data *)tree, max_code, s->bl_count);
--}
--
--/* ===========================================================================
-- * Scan a literal or distance tree to determine the frequencies of the codes
-- * in the bit length tree.
-- */
--local void scan_tree (s, tree, max_code)
--    deflate_state *s;
--    ct_data *tree;   /* the tree to be scanned */
--    int max_code;    /* and its largest code of non zero frequency */
--{
--    int n;                     /* iterates over all tree elements */
--    int prevlen = -1;          /* last emitted length */
--    int curlen;                /* length of current code */
--    int nextlen = tree[0].Len; /* length of next code */
--    int count = 0;             /* repeat count of the current code */
--    int max_count = 7;         /* max repeat count */
--    int min_count = 4;         /* min repeat count */
--
--    if (nextlen == 0) max_count = 138, min_count = 3;
--    tree[max_code+1].Len = (ush)0xffff; /* guard */
--
--    for (n = 0; n <= max_code; n++) {
--        curlen = nextlen; nextlen = tree[n+1].Len;
--        if (++count < max_count && curlen == nextlen) {
--            continue;
--        } else if (count < min_count) {
--            s->bl_tree[curlen].Freq += count;
--        } else if (curlen != 0) {
--            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
--            s->bl_tree[REP_3_6].Freq++;
--        } else if (count <= 10) {
--            s->bl_tree[REPZ_3_10].Freq++;
--        } else {
--            s->bl_tree[REPZ_11_138].Freq++;
--        }
--        count = 0; prevlen = curlen;
--        if (nextlen == 0) {
--            max_count = 138, min_count = 3;
--        } else if (curlen == nextlen) {
--            max_count = 6, min_count = 3;
--        } else {
--            max_count = 7, min_count = 4;
--        }
--    }
--}
--
--/* ===========================================================================
-- * Send a literal or distance tree in compressed form, using the codes in
-- * bl_tree.
-- */
--local void send_tree (s, tree, max_code)
--    deflate_state *s;
--    ct_data *tree; /* the tree to be scanned */
--    int max_code;       /* and its largest code of non zero frequency */
--{
--    int n;                     /* iterates over all tree elements */
--    int prevlen = -1;          /* last emitted length */
--    int curlen;                /* length of current code */
--    int nextlen = tree[0].Len; /* length of next code */
--    int count = 0;             /* repeat count of the current code */
--    int max_count = 7;         /* max repeat count */
--    int min_count = 4;         /* min repeat count */
--
--    /* tree[max_code+1].Len = -1; */  /* guard already set */
--    if (nextlen == 0) max_count = 138, min_count = 3;
--
--    for (n = 0; n <= max_code; n++) {
--        curlen = nextlen; nextlen = tree[n+1].Len;
--        if (++count < max_count && curlen == nextlen) {
--            continue;
--        } else if (count < min_count) {
--            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
--
--        } else if (curlen != 0) {
--            if (curlen != prevlen) {
--                send_code(s, curlen, s->bl_tree); count--;
--            }
--            Assert(count >= 3 && count <= 6, " 3_6?");
--            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
--
--        } else if (count <= 10) {
--            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
--
--        } else {
--            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
--        }
--        count = 0; prevlen = curlen;
--        if (nextlen == 0) {
--            max_count = 138, min_count = 3;
--        } else if (curlen == nextlen) {
--            max_count = 6, min_count = 3;
--        } else {
--            max_count = 7, min_count = 4;
--        }
--    }
--}
--
--/* ===========================================================================
-- * Construct the Huffman tree for the bit lengths and return the index in
-- * bl_order of the last bit length code to send.
-- */
--local int build_bl_tree(s)
--    deflate_state *s;
--{
--    int max_blindex;  /* index of last bit length code of non zero freq */
--
--    /* Determine the bit length frequencies for literal and distance trees */
--    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
--    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
--
--    /* Build the bit length tree: */
--    build_tree(s, (tree_desc *)(&(s->bl_desc)));
--    /* opt_len now includes the length of the tree representations, except
--     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
--     */
--
--    /* Determine the number of bit length codes to send. The pkzip format
--     * requires that at least 4 bit length codes be sent. (appnote.txt says
--     * 3 but the actual value used is 4.)
--     */
--    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
--        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
--    }
--    /* Update opt_len to include the bit length tree and counts */
--    s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
--    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
--            s->opt_len, s->static_len));
--
--    return max_blindex;
--}
--
--/* ===========================================================================
-- * Send the header for a block using dynamic Huffman trees: the counts, the
-- * lengths of the bit length codes, the literal tree and the distance tree.
-- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
-- */
--local void send_all_trees(s, lcodes, dcodes, blcodes)
--    deflate_state *s;
--    int lcodes, dcodes, blcodes; /* number of codes for each tree */
--{
--    int rank;                    /* index in bl_order */
--
--    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
--    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
--            "too many codes");
--    Tracev((stderr, "\nbl counts: "));
--    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
--    send_bits(s, dcodes-1,   5);
--    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
--    for (rank = 0; rank < blcodes; rank++) {
--        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
--        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
--    }
--    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
--
--    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
--    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
--
--    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
--    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
--}
--
--/* ===========================================================================
-- * Send a stored block
-- */
--void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
--    deflate_state *s;
--    charf *buf;       /* input block */
--    ulg stored_len;   /* length of input block */
--    int last;         /* one if this is the last block for a file */
--{
--    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
--    bi_windup(s);        /* align on byte boundary */
--    put_short(s, (ush)stored_len);
--    put_short(s, (ush)~stored_len);
--    zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
--    s->pending += stored_len;
--#ifdef ZLIB_DEBUG
--    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
--    s->compressed_len += (stored_len + 4) << 3;
--    s->bits_sent += 2*16;
--    s->bits_sent += stored_len<<3;
--#endif
--}
--
--/* ===========================================================================
-- * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
-- */
--void ZLIB_INTERNAL _tr_flush_bits(s)
--    deflate_state *s;
--{
--    bi_flush(s);
--}
--
--/* ===========================================================================
-- * Send one empty static block to give enough lookahead for inflate.
-- * This takes 10 bits, of which 7 may remain in the bit buffer.
-- */
--void ZLIB_INTERNAL _tr_align(s)
--    deflate_state *s;
--{
--    send_bits(s, STATIC_TREES<<1, 3);
--    send_code(s, END_BLOCK, static_ltree);
--#ifdef ZLIB_DEBUG
--    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
--#endif
--    bi_flush(s);
--}
--
--/* ===========================================================================
-- * Determine the best encoding for the current block: dynamic trees, static
-- * trees or store, and write out the encoded block.
-- */
--void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
--    deflate_state *s;
--    charf *buf;       /* input block, or NULL if too old */
--    ulg stored_len;   /* length of input block */
--    int last;         /* one if this is the last block for a file */
--{
--    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
--    int max_blindex = 0;  /* index of last bit length code of non zero freq */
--
--    /* Build the Huffman trees unless a stored block is forced */
--    if (s->level > 0) {
--
--        /* Check if the file is binary or text */
--        if (s->strm->data_type == Z_UNKNOWN)
--            s->strm->data_type = detect_data_type(s);
--
--        /* Construct the literal and distance trees */
--        build_tree(s, (tree_desc *)(&(s->l_desc)));
--        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
--                s->static_len));
--
--        build_tree(s, (tree_desc *)(&(s->d_desc)));
--        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
--                s->static_len));
--        /* At this point, opt_len and static_len are the total bit lengths of
--         * the compressed block data, excluding the tree representations.
--         */
--
--        /* Build the bit length tree for the above two trees, and get the index
--         * in bl_order of the last bit length code to send.
--         */
--        max_blindex = build_bl_tree(s);
--
--        /* Determine the best encoding. Compute the block lengths in bytes. */
--        opt_lenb = (s->opt_len+3+7)>>3;
--        static_lenb = (s->static_len+3+7)>>3;
--
--        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
--                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
--                s->last_lit));
--
--        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
--
--    } else {
--        Assert(buf != (char*)0, "lost buf");
--        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
--    }
--
--#ifdef FORCE_STORED
--    if (buf != (char*)0) { /* force stored block */
--#else
--    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
--                       /* 4: two words for the lengths */
--#endif
--        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
--         * Otherwise we can't have processed more than WSIZE input bytes since
--         * the last block flush, because compression would have been
--         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
--         * transform a block into a stored block.
--         */
--        _tr_stored_block(s, buf, stored_len, last);
--
--#ifdef FORCE_STATIC
--    } else if (static_lenb >= 0) { /* force static trees */
--#else
--    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
--#endif
--        send_bits(s, (STATIC_TREES<<1)+last, 3);
--        compress_block(s, (const ct_data *)static_ltree,
--                       (const ct_data *)static_dtree);
--#ifdef ZLIB_DEBUG
--        s->compressed_len += 3 + s->static_len;
--#endif
--    } else {
--        send_bits(s, (DYN_TREES<<1)+last, 3);
--        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
--                       max_blindex+1);
--        compress_block(s, (const ct_data *)s->dyn_ltree,
--                       (const ct_data *)s->dyn_dtree);
--#ifdef ZLIB_DEBUG
--        s->compressed_len += 3 + s->opt_len;
--#endif
--    }
--    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
--    /* The above check is made mod 2^32, for files larger than 512 MB
--     * and uLong implemented on 32 bits.
--     */
--    init_block(s);
--
--    if (last) {
--        bi_windup(s);
--#ifdef ZLIB_DEBUG
--        s->compressed_len += 7;  /* align on byte boundary */
--#endif
--    }
--    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
--           s->compressed_len-7*last));
--}
--
--/* ===========================================================================
-- * Save the match info and tally the frequency counts. Return true if
-- * the current block must be flushed.
-- */
--int ZLIB_INTERNAL _tr_tally (s, dist, lc)
--    deflate_state *s;
--    unsigned dist;  /* distance of matched string */
--    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
--{
--    s->d_buf[s->last_lit] = (ush)dist;
--    s->l_buf[s->last_lit++] = (uch)lc;
--    if (dist == 0) {
--        /* lc is the unmatched char */
--        s->dyn_ltree[lc].Freq++;
--    } else {
--        s->matches++;
--        /* Here, lc is the match length - MIN_MATCH */
--        dist--;             /* dist = match distance - 1 */
--        Assert((ush)dist < (ush)MAX_DIST(s) &&
--               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
--               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
--
--        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
--        s->dyn_dtree[d_code(dist)].Freq++;
--    }
--
--#ifdef TRUNCATE_BLOCK
--    /* Try to guess if it is profitable to stop the current block here */
--    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
--        /* Compute an upper bound for the compressed length */
--        ulg out_length = (ulg)s->last_lit*8L;
--        ulg in_length = (ulg)((long)s->strstart - s->block_start);
--        int dcode;
--        for (dcode = 0; dcode < D_CODES; dcode++) {
--            out_length += (ulg)s->dyn_dtree[dcode].Freq *
--                (5L+extra_dbits[dcode]);
--        }
--        out_length >>= 3;
--        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
--               s->last_lit, in_length, out_length,
--               100L - out_length*100L/in_length));
--        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
--    }
--#endif
--    return (s->last_lit == s->lit_bufsize-1);
--    /* We avoid equality with lit_bufsize because of wraparound at 64K
--     * on 16 bit machines and because stored blocks are restricted to
--     * 64K-1 bytes.
--     */
--}
--
--/* ===========================================================================
-- * Send the block data compressed using the given Huffman trees
-- */
--local void compress_block(s, ltree, dtree)
--    deflate_state *s;
--    const ct_data *ltree; /* literal tree */
--    const ct_data *dtree; /* distance tree */
--{
--    unsigned dist;      /* distance of matched string */
--    int lc;             /* match length or unmatched char (if dist == 0) */
--    unsigned lx = 0;    /* running index in l_buf */
--    unsigned code;      /* the code to send */
--    int extra;          /* number of extra bits to send */
--
--    if (s->last_lit != 0) do {
--        dist = s->d_buf[lx];
--        lc = s->l_buf[lx++];
--        if (dist == 0) {
--            send_code(s, lc, ltree); /* send a literal byte */
--            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
--        } else {
--            /* Here, lc is the match length - MIN_MATCH */
--            code = _length_code[lc];
--            send_code(s, code+LITERALS+1, ltree); /* send the length code */
--            extra = extra_lbits[code];
--            if (extra != 0) {
--                lc -= base_length[code];
--                send_bits(s, lc, extra);       /* send the extra length bits */
--            }
--            dist--; /* dist is now the match distance - 1 */
--            code = d_code(dist);
--            Assert (code < D_CODES, "bad d_code");
--
--            send_code(s, code, dtree);       /* send the distance code */
--            extra = extra_dbits[code];
--            if (extra != 0) {
--                dist -= (unsigned)base_dist[code];
--                send_bits(s, dist, extra);   /* send the extra distance bits */
--            }
--        } /* literal or match pair ? */
--
--        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
--        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
--               "pendingBuf overflow");
--
--    } while (lx < s->last_lit);
--
--    send_code(s, END_BLOCK, ltree);
--}
--
--/* ===========================================================================
-- * Check if the data type is TEXT or BINARY, using the following algorithm:
-- * - TEXT if the two conditions below are satisfied:
-- *    a) There are no non-portable control characters belonging to the
-- *       "black list" (0..6, 14..25, 28..31).
-- *    b) There is at least one printable character belonging to the
-- *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
-- * - BINARY otherwise.
-- * - The following partially-portable control characters form a
-- *   "gray list" that is ignored in this detection algorithm:
-- *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
-- * IN assertion: the fields Freq of dyn_ltree are set.
-- */
--local int detect_data_type(s)
--    deflate_state *s;
--{
--    /* black_mask is the bit mask of black-listed bytes
--     * set bits 0..6, 14..25, and 28..31
--     * 0xf3ffc07f = binary 11110011111111111100000001111111
--     */
--    unsigned long black_mask = 0xf3ffc07fUL;
--    int n;
--
--    /* Check for non-textual ("black-listed") bytes. */
--    for (n = 0; n <= 31; n++, black_mask >>= 1)
--        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
--            return Z_BINARY;
--
--    /* Check for textual ("white-listed") bytes. */
--    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
--            || s->dyn_ltree[13].Freq != 0)
--        return Z_TEXT;
--    for (n = 32; n < LITERALS; n++)
--        if (s->dyn_ltree[n].Freq != 0)
--            return Z_TEXT;
--
--    /* There are no "black-listed" or "white-listed" bytes:
--     * this stream either is empty or has tolerated ("gray-listed") bytes only.
--     */
--    return Z_BINARY;
--}
--
--/* ===========================================================================
-- * Reverse the first len bits of a code, using straightforward code (a faster
-- * method would use a table)
-- * IN assertion: 1 <= len <= 15
-- */
--local unsigned bi_reverse(code, len)
--    unsigned code; /* the value to invert */
--    int len;       /* its bit length */
--{
--    register unsigned res = 0;
--    do {
--        res |= code & 1;
--        code >>= 1, res <<= 1;
--    } while (--len > 0);
--    return res >> 1;
--}
--
--/* ===========================================================================
-- * Flush the bit buffer, keeping at most 7 bits in it.
-- */
--local void bi_flush(s)
--    deflate_state *s;
--{
--    if (s->bi_valid == 16) {
--        put_short(s, s->bi_buf);
--        s->bi_buf = 0;
--        s->bi_valid = 0;
--    } else if (s->bi_valid >= 8) {
--        put_byte(s, (Byte)s->bi_buf);
--        s->bi_buf >>= 8;
--        s->bi_valid -= 8;
--    }
--}
--
--/* ===========================================================================
-- * Flush the bit buffer and align the output on a byte boundary
-- */
--local void bi_windup(s)
--    deflate_state *s;
--{
--    if (s->bi_valid > 8) {
--        put_short(s, s->bi_buf);
--    } else if (s->bi_valid > 0) {
--        put_byte(s, (Byte)s->bi_buf);
--    }
--    s->bi_buf = 0;
--    s->bi_valid = 0;
--#ifdef ZLIB_DEBUG
--    s->bits_sent = (s->bits_sent+7) & ~7;
--#endif
--}
diff --cc zlib/trees.h
index d35639d82a27807e49ea35c334f8bbcf64720f82,d35639d82a27807e49ea35c334f8bbcf64720f82..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,128 -1,128 +1,0 @@@
--/* header created automatically with -DGEN_TREES_H */
--
--local const ct_data static_ltree[L_CODES+2] = {
--{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
--{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
--{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
--{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
--{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
--{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
--{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
--{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
--{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
--{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
--{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
--{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
--{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
--{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
--{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
--{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
--{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
--{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
--{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
--{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
--{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
--{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
--{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
--{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
--{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
--{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
--{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
--{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
--{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
--{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
--{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
--{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
--{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
--{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
--{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
--{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
--{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
--{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
--{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
--{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
--{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
--{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
--{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
--{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
--{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
--{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
--{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
--{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
--{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
--{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
--{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
--{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
--{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
--{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
--{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
--{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
--{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
--{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
--};
--
--local const ct_data static_dtree[D_CODES] = {
--{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
--{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
--{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
--{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
--{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
--{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
--};
--
--const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
-- 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
-- 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
--10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
--11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
--12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
--13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
--13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
--14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
--14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
--14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
--15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
--15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
--15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
--18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
--23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
--24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
--26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
--26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
--27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
--27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
--28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
--28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
--28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
--29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
--29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
--29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
--};
--
--const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
-- 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
--13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
--17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
--19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
--21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
--22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
--23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
--24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
--25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
--25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
--26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
--26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
--27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
--};
--
--local const int base_length[LENGTH_CODES] = {
--0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
--64, 80, 96, 112, 128, 160, 192, 224, 0
--};
--
--local const int base_dist[D_CODES] = {
--    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
--   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
-- 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
--};
--
diff --cc zlib/uncompr.c
index f03a1a865e347d10ac16f6a70b2bc2fdc5235f9c,f03a1a865e347d10ac16f6a70b2bc2fdc5235f9c..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,93 -1,93 +1,0 @@@
--/* uncompr.c -- decompress a memory buffer
-- * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* @(#) $Id$ */
--
--#define ZLIB_INTERNAL
--#include "zlib.h"
--
--/* ===========================================================================
--     Decompresses the source buffer into the destination buffer.  *sourceLen is
--   the byte length of the source buffer. Upon entry, *destLen is the total size
--   of the destination buffer, which must be large enough to hold the entire
--   uncompressed data. (The size of the uncompressed data must have been saved
--   previously by the compressor and transmitted to the decompressor by some
--   mechanism outside the scope of this compression library.) Upon exit,
--   *destLen is the size of the decompressed data and *sourceLen is the number
--   of source bytes consumed. Upon return, source + *sourceLen points to the
--   first unused input byte.
--
--     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_BUF_ERROR if there was not enough room in the output buffer, or
--   Z_DATA_ERROR if the input data was corrupted, including if the input data is
--   an incomplete zlib stream.
--*/
--int ZEXPORT uncompress2 (dest, destLen, source, sourceLen)
--    Bytef *dest;
--    uLongf *destLen;
--    const Bytef *source;
--    uLong *sourceLen;
--{
--    z_stream stream;
--    int err;
--    const uInt max = (uInt)-1;
--    uLong len, left;
--    Byte buf[1];    /* for detection of incomplete stream when *destLen == 0 */
--
--    len = *sourceLen;
--    if (*destLen) {
--        left = *destLen;
--        *destLen = 0;
--    }
--    else {
--        left = 1;
--        dest = buf;
--    }
--
--    stream.next_in = (z_const Bytef *)source;
--    stream.avail_in = 0;
--    stream.zalloc = (alloc_func)0;
--    stream.zfree = (free_func)0;
--    stream.opaque = (voidpf)0;
--
--    err = inflateInit(&stream);
--    if (err != Z_OK) return err;
--
--    stream.next_out = dest;
--    stream.avail_out = 0;
--
--    do {
--        if (stream.avail_out == 0) {
--            stream.avail_out = left > (uLong)max ? max : (uInt)left;
--            left -= stream.avail_out;
--        }
--        if (stream.avail_in == 0) {
--            stream.avail_in = len > (uLong)max ? max : (uInt)len;
--            len -= stream.avail_in;
--        }
--        err = inflate(&stream, Z_NO_FLUSH);
--    } while (err == Z_OK);
--
--    *sourceLen -= len + stream.avail_in;
--    if (dest != buf)
--        *destLen = stream.total_out;
--    else if (stream.total_out && err == Z_BUF_ERROR)
--        left = 1;
--
--    inflateEnd(&stream);
--    return err == Z_STREAM_END ? Z_OK :
--           err == Z_NEED_DICT ? Z_DATA_ERROR  :
--           err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
--           err;
--}
--
--int ZEXPORT uncompress (dest, destLen, source, sourceLen)
--    Bytef *dest;
--    uLongf *destLen;
--    const Bytef *source;
--    uLong sourceLen;
--{
--    return uncompress2(dest, destLen, source, &sourceLen);
--}
diff --cc zlib/zconf.h
index 393c12664983b2c20dc7aecf22dd2e1a1d157d3f,5e1d68a004e9744cb35f9d5a2fe94fd4dbcb7f76..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,540 -1,534 +1,0 @@@
--/* zconf.h -- configuration of the zlib compression library
-- * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* @(#) $Id$ */
--
--#ifndef ZCONF_H
--#define ZCONF_H
- /* Start GPSBabel local */
- #ifdef HAVE_CONFIG_H
- #include "config.h"
- #endif
- /* end GPSBabel local */
--
--/*
-- * If you *really* need a unique prefix for all types and library functions,
-- * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
-- * Even better than compiling with -DZ_PREFIX would be to use configure to set
-- * this permanently in zconf.h using "./configure --zprefix".
-- */
--#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
--#  define Z_PREFIX_SET
--
--/* all linked symbols and init macros */
--#  define _dist_code            z__dist_code
--#  define _length_code          z__length_code
--#  define _tr_align             z__tr_align
--#  define _tr_flush_bits        z__tr_flush_bits
--#  define _tr_flush_block       z__tr_flush_block
--#  define _tr_init              z__tr_init
--#  define _tr_stored_block      z__tr_stored_block
--#  define _tr_tally             z__tr_tally
--#  define adler32               z_adler32
--#  define adler32_combine       z_adler32_combine
--#  define adler32_combine64     z_adler32_combine64
--#  define adler32_z             z_adler32_z
--#  ifndef Z_SOLO
--#    define compress              z_compress
--#    define compress2             z_compress2
--#    define compressBound         z_compressBound
--#  endif
--#  define crc32                 z_crc32
--#  define crc32_combine         z_crc32_combine
--#  define crc32_combine64       z_crc32_combine64
--#  define crc32_z               z_crc32_z
--#  define deflate               z_deflate
--#  define deflateBound          z_deflateBound
--#  define deflateCopy           z_deflateCopy
--#  define deflateEnd            z_deflateEnd
--#  define deflateGetDictionary  z_deflateGetDictionary
--#  define deflateInit           z_deflateInit
--#  define deflateInit2          z_deflateInit2
--#  define deflateInit2_         z_deflateInit2_
--#  define deflateInit_          z_deflateInit_
--#  define deflateParams         z_deflateParams
--#  define deflatePending        z_deflatePending
--#  define deflatePrime          z_deflatePrime
--#  define deflateReset          z_deflateReset
--#  define deflateResetKeep      z_deflateResetKeep
--#  define deflateSetDictionary  z_deflateSetDictionary
--#  define deflateSetHeader      z_deflateSetHeader
--#  define deflateTune           z_deflateTune
--#  define deflate_copyright     z_deflate_copyright
--#  define get_crc_table         z_get_crc_table
--#  ifndef Z_SOLO
--#    define gz_error              z_gz_error
--#    define gz_intmax             z_gz_intmax
--#    define gz_strwinerror        z_gz_strwinerror
--#    define gzbuffer              z_gzbuffer
--#    define gzclearerr            z_gzclearerr
--#    define gzclose               z_gzclose
--#    define gzclose_r             z_gzclose_r
--#    define gzclose_w             z_gzclose_w
--#    define gzdirect              z_gzdirect
--#    define gzdopen               z_gzdopen
--#    define gzeof                 z_gzeof
--#    define gzerror               z_gzerror
--#    define gzflush               z_gzflush
--#    define gzfread               z_gzfread
--#    define gzfwrite              z_gzfwrite
--#    define gzgetc                z_gzgetc
--#    define gzgetc_               z_gzgetc_
--#    define gzgets                z_gzgets
--#    define gzoffset              z_gzoffset
--#    define gzoffset64            z_gzoffset64
--#    define gzopen                z_gzopen
--#    define gzopen64              z_gzopen64
--#    ifdef _WIN32
--#      define gzopen_w              z_gzopen_w
--#    endif
--#    define gzprintf              z_gzprintf
--#    define gzputc                z_gzputc
--#    define gzputs                z_gzputs
--#    define gzread                z_gzread
--#    define gzrewind              z_gzrewind
--#    define gzseek                z_gzseek
--#    define gzseek64              z_gzseek64
--#    define gzsetparams           z_gzsetparams
--#    define gztell                z_gztell
--#    define gztell64              z_gztell64
--#    define gzungetc              z_gzungetc
--#    define gzvprintf             z_gzvprintf
--#    define gzwrite               z_gzwrite
--#  endif
--#  define inflate               z_inflate
--#  define inflateBack           z_inflateBack
--#  define inflateBackEnd        z_inflateBackEnd
--#  define inflateBackInit       z_inflateBackInit
--#  define inflateBackInit_      z_inflateBackInit_
--#  define inflateCodesUsed      z_inflateCodesUsed
--#  define inflateCopy           z_inflateCopy
--#  define inflateEnd            z_inflateEnd
--#  define inflateGetDictionary  z_inflateGetDictionary
--#  define inflateGetHeader      z_inflateGetHeader
--#  define inflateInit           z_inflateInit
--#  define inflateInit2          z_inflateInit2
--#  define inflateInit2_         z_inflateInit2_
--#  define inflateInit_          z_inflateInit_
--#  define inflateMark           z_inflateMark
--#  define inflatePrime          z_inflatePrime
--#  define inflateReset          z_inflateReset
--#  define inflateReset2         z_inflateReset2
--#  define inflateResetKeep      z_inflateResetKeep
--#  define inflateSetDictionary  z_inflateSetDictionary
--#  define inflateSync           z_inflateSync
--#  define inflateSyncPoint      z_inflateSyncPoint
--#  define inflateUndermine      z_inflateUndermine
--#  define inflateValidate       z_inflateValidate
--#  define inflate_copyright     z_inflate_copyright
--#  define inflate_fast          z_inflate_fast
--#  define inflate_table         z_inflate_table
--#  ifndef Z_SOLO
--#    define uncompress            z_uncompress
--#    define uncompress2           z_uncompress2
--#  endif
--#  define zError                z_zError
--#  ifndef Z_SOLO
--#    define zcalloc               z_zcalloc
--#    define zcfree                z_zcfree
--#  endif
--#  define zlibCompileFlags      z_zlibCompileFlags
--#  define zlibVersion           z_zlibVersion
--
--/* all zlib typedefs in zlib.h and zconf.h */
--#  define Byte                  z_Byte
--#  define Bytef                 z_Bytef
--#  define alloc_func            z_alloc_func
--#  define charf                 z_charf
--#  define free_func             z_free_func
--#  ifndef Z_SOLO
--#    define gzFile                z_gzFile
--#  endif
--#  define gz_header             z_gz_header
--#  define gz_headerp            z_gz_headerp
--#  define in_func               z_in_func
--#  define intf                  z_intf
--#  define out_func              z_out_func
--#  define uInt                  z_uInt
--#  define uIntf                 z_uIntf
--#  define uLong                 z_uLong
--#  define uLongf                z_uLongf
--#  define voidp                 z_voidp
--#  define voidpc                z_voidpc
--#  define voidpf                z_voidpf
--
--/* all zlib structs in zlib.h and zconf.h */
--#  define gz_header_s           z_gz_header_s
--#  define internal_state        z_internal_state
--
--#endif
--
--#if defined(__MSDOS__) && !defined(MSDOS)
--#  define MSDOS
--#endif
--#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
--#  define OS2
--#endif
--#if defined(_WINDOWS) && !defined(WINDOWS)
--#  define WINDOWS
--#endif
--#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
--#  ifndef WIN32
--#    define WIN32
--#  endif
--#endif
--#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
--#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
--#    ifndef SYS16BIT
--#      define SYS16BIT
--#    endif
--#  endif
--#endif
--
--/*
-- * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
-- * than 64k bytes at a time (needed on systems with 16-bit int).
-- */
--#ifdef SYS16BIT
--#  define MAXSEG_64K
--#endif
--#ifdef MSDOS
--#  define UNALIGNED_OK
--#endif
--
--#ifdef __STDC_VERSION__
--#  ifndef STDC
--#    define STDC
--#  endif
--#  if __STDC_VERSION__ >= 199901L
--#    ifndef STDC99
--#      define STDC99
--#    endif
--#  endif
--#endif
--#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
--#  define STDC
--#endif
--#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
--#  define STDC
--#endif
--#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
--#  define STDC
--#endif
--#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
--#  define STDC
--#endif
--
--#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
--#  define STDC
--#endif
--
--#ifndef STDC
--#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
--#    define const       /* note: need a more gentle solution here */
--#  endif
--#endif
--
--#if defined(ZLIB_CONST) && !defined(z_const)
--#  define z_const const
--#else
--#  define z_const
--#endif
--
--#ifdef Z_SOLO
--   typedef unsigned long z_size_t;
--#else
--#  define z_longlong long long
--#  if defined(NO_SIZE_T)
--     typedef unsigned NO_SIZE_T z_size_t;
--#  elif defined(STDC)
--#    include <stddef.h>
--     typedef size_t z_size_t;
--#  else
--     typedef unsigned long z_size_t;
--#  endif
--#  undef z_longlong
--#endif
--
--/* Maximum value for memLevel in deflateInit2 */
--#ifndef MAX_MEM_LEVEL
--#  ifdef MAXSEG_64K
--#    define MAX_MEM_LEVEL 8
--#  else
--#    define MAX_MEM_LEVEL 9
--#  endif
--#endif
--
--/* Maximum value for windowBits in deflateInit2 and inflateInit2.
-- * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
-- * created by gzip. (Files created by minigzip can still be extracted by
-- * gzip.)
-- */
--#ifndef MAX_WBITS
--#  define MAX_WBITS   15 /* 32K LZ77 window */
--#endif
--
--/* The memory requirements for deflate are (in bytes):
--            (1 << (windowBits+2)) +  (1 << (memLevel+9))
-- that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
-- plus a few kilobytes for small objects. For example, if you want to reduce
-- the default memory requirements from 256K to 128K, compile with
--     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
-- Of course this will generally degrade compression (there's no free lunch).
--
--   The memory requirements for inflate are (in bytes) 1 << windowBits
-- that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
-- for small objects.
--*/
--
--                        /* Type declarations */
--
--#ifndef OF /* function prototypes */
--#  ifdef STDC
--#    define OF(args)  args
--#  else
--#    define OF(args)  ()
--#  endif
--#endif
--
--#ifndef Z_ARG /* function prototypes for stdarg */
--#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#    define Z_ARG(args)  args
--#  else
--#    define Z_ARG(args)  ()
--#  endif
--#endif
--
--/* The following definitions for FAR are needed only for MSDOS mixed
-- * model programming (small or medium model with some far allocations).
-- * This was tested only with MSC; for other MSDOS compilers you may have
-- * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
-- * just define FAR to be empty.
-- */
--#ifdef SYS16BIT
--#  if defined(M_I86SM) || defined(M_I86MM)
--     /* MSC small or medium model */
--#    define SMALL_MEDIUM
--#    ifdef _MSC_VER
--#      define FAR _far
--#    else
--#      define FAR far
--#    endif
--#  endif
--#  if (defined(__SMALL__) || defined(__MEDIUM__))
--     /* Turbo C small or medium model */
--#    define SMALL_MEDIUM
--#    ifdef __BORLANDC__
--#      define FAR _far
--#    else
--#      define FAR far
--#    endif
--#  endif
--#endif
--
--#if defined(WINDOWS) || defined(WIN32)
--   /* If building or using zlib as a DLL, define ZLIB_DLL.
--    * This is not mandatory, but it offers a little performance increase.
--    */
--#  ifdef ZLIB_DLL
--#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
--#      ifdef ZLIB_INTERNAL
--#        define ZEXTERN extern __declspec(dllexport)
--#      else
--#        define ZEXTERN extern __declspec(dllimport)
--#      endif
--#    endif
--#  endif  /* ZLIB_DLL */
--   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
--    * define ZLIB_WINAPI.
--    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
--    */
--#  ifdef ZLIB_WINAPI
--#    ifdef FAR
--#      undef FAR
--#    endif
--#    include <windows.h>
--     /* No need for _export, use ZLIB.DEF instead. */
--     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
--#    define ZEXPORT WINAPI
--#    ifdef WIN32
--#      define ZEXPORTVA WINAPIV
--#    else
--#      define ZEXPORTVA FAR CDECL
--#    endif
--#  endif
--#endif
--
--#if defined (__BEOS__)
--#  ifdef ZLIB_DLL
--#    ifdef ZLIB_INTERNAL
--#      define ZEXPORT   __declspec(dllexport)
--#      define ZEXPORTVA __declspec(dllexport)
--#    else
--#      define ZEXPORT   __declspec(dllimport)
--#      define ZEXPORTVA __declspec(dllimport)
--#    endif
--#  endif
--#endif
--
--#ifndef ZEXTERN
--#  define ZEXTERN extern
--#endif
--#ifndef ZEXPORT
--#  define ZEXPORT
--#endif
--#ifndef ZEXPORTVA
--#  define ZEXPORTVA
--#endif
--
--#ifndef FAR
--#  define FAR
--#endif
--
--#if !defined(__MACTYPES__)
--typedef unsigned char  Byte;  /* 8 bits */
--#endif
--typedef unsigned int   uInt;  /* 16 bits or more */
--typedef unsigned long  uLong; /* 32 bits or more */
--
--#ifdef SMALL_MEDIUM
--   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
--#  define Bytef Byte FAR
--#else
--   typedef Byte  FAR Bytef;
--#endif
--typedef char  FAR charf;
--typedef int   FAR intf;
--typedef uInt  FAR uIntf;
--typedef uLong FAR uLongf;
--
--#ifdef STDC
--   typedef void const *voidpc;
--   typedef void FAR   *voidpf;
--   typedef void       *voidp;
--#else
--   typedef Byte const *voidpc;
--   typedef Byte FAR   *voidpf;
--   typedef Byte       *voidp;
--#endif
--
--#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
--#  include <limits.h>
--#  if (UINT_MAX == 0xffffffffUL)
--#    define Z_U4 unsigned
--#  elif (ULONG_MAX == 0xffffffffUL)
--#    define Z_U4 unsigned long
--#  elif (USHRT_MAX == 0xffffffffUL)
--#    define Z_U4 unsigned short
--#  endif
--#endif
--
--#ifdef Z_U4
--   typedef Z_U4 z_crc_t;
--#else
--   typedef unsigned long z_crc_t;
--#endif
--
--#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
--#  define Z_HAVE_UNISTD_H
--#endif
--
--#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
--#  define Z_HAVE_STDARG_H
--#endif
--
--#ifdef STDC
--#  ifndef Z_SOLO
--#    include <sys/types.h>      /* for off_t */
--#  endif
--#endif
--
--#if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#  ifndef Z_SOLO
--#    include <stdarg.h>         /* for va_list */
--#  endif
--#endif
--
--#ifdef _WIN32
--#  ifndef Z_SOLO
--#    include <stddef.h>         /* for wchar_t */
--#  endif
--#endif
--
--/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
-- * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
-- * though the former does not conform to the LFS document), but considering
-- * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
-- * equivalently requesting no 64-bit operations
-- */
--#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
--#  undef _LARGEFILE64_SOURCE
--#endif
--
--#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
--#  define Z_HAVE_UNISTD_H
--#endif
--#ifndef Z_SOLO
--#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
--#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
--#    ifdef VMS
--#      include <unixio.h>       /* for off_t */
--#    endif
--#    ifndef z_off_t
--#      define z_off_t off_t
--#    endif
--#  endif
--#endif
--
--#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
--#  define Z_LFS64
--#endif
--
--#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
--#  define Z_LARGE64
--#endif
--
--#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
--#  define Z_WANT64
--#endif
--
--#if !defined(SEEK_SET) && !defined(Z_SOLO)
--#  define SEEK_SET        0       /* Seek from beginning of file.  */
--#  define SEEK_CUR        1       /* Seek from current position.  */
--#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
--#endif
--
--#ifndef z_off_t
--#  define z_off_t long
--#endif
--
--#if !defined(_WIN32) && defined(Z_LARGE64)
--#  define z_off64_t off64_t
--#else
--#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
--#    define z_off64_t __int64
--#  else
--#    define z_off64_t z_off_t
--#  endif
--#endif
--
--/* MVS linker does not support external names larger than 8 bytes */
--#if defined(__MVS__)
--  #pragma map(deflateInit_,"DEIN")
--  #pragma map(deflateInit2_,"DEIN2")
--  #pragma map(deflateEnd,"DEEND")
--  #pragma map(deflateBound,"DEBND")
--  #pragma map(inflateInit_,"ININ")
--  #pragma map(inflateInit2_,"ININ2")
--  #pragma map(inflateEnd,"INEND")
--  #pragma map(inflateSync,"INSY")
--  #pragma map(inflateSetDictionary,"INSEDI")
--  #pragma map(compressBound,"CMBND")
--  #pragma map(inflate_table,"INTABL")
--  #pragma map(inflate_fast,"INFA")
--  #pragma map(inflate_copyright,"INCOPY")
--#endif
--
--#endif /* ZCONF_H */
diff --cc zlib/zconf.in.h
index 5e1d68a004e9744cb35f9d5a2fe94fd4dbcb7f76,5e1d68a004e9744cb35f9d5a2fe94fd4dbcb7f76..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,534 -1,534 +1,0 @@@
--/* zconf.h -- configuration of the zlib compression library
-- * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* @(#) $Id$ */
--
--#ifndef ZCONF_H
--#define ZCONF_H
--
--/*
-- * If you *really* need a unique prefix for all types and library functions,
-- * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
-- * Even better than compiling with -DZ_PREFIX would be to use configure to set
-- * this permanently in zconf.h using "./configure --zprefix".
-- */
--#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
--#  define Z_PREFIX_SET
--
--/* all linked symbols and init macros */
--#  define _dist_code            z__dist_code
--#  define _length_code          z__length_code
--#  define _tr_align             z__tr_align
--#  define _tr_flush_bits        z__tr_flush_bits
--#  define _tr_flush_block       z__tr_flush_block
--#  define _tr_init              z__tr_init
--#  define _tr_stored_block      z__tr_stored_block
--#  define _tr_tally             z__tr_tally
--#  define adler32               z_adler32
--#  define adler32_combine       z_adler32_combine
--#  define adler32_combine64     z_adler32_combine64
--#  define adler32_z             z_adler32_z
--#  ifndef Z_SOLO
--#    define compress              z_compress
--#    define compress2             z_compress2
--#    define compressBound         z_compressBound
--#  endif
--#  define crc32                 z_crc32
--#  define crc32_combine         z_crc32_combine
--#  define crc32_combine64       z_crc32_combine64
--#  define crc32_z               z_crc32_z
--#  define deflate               z_deflate
--#  define deflateBound          z_deflateBound
--#  define deflateCopy           z_deflateCopy
--#  define deflateEnd            z_deflateEnd
--#  define deflateGetDictionary  z_deflateGetDictionary
--#  define deflateInit           z_deflateInit
--#  define deflateInit2          z_deflateInit2
--#  define deflateInit2_         z_deflateInit2_
--#  define deflateInit_          z_deflateInit_
--#  define deflateParams         z_deflateParams
--#  define deflatePending        z_deflatePending
--#  define deflatePrime          z_deflatePrime
--#  define deflateReset          z_deflateReset
--#  define deflateResetKeep      z_deflateResetKeep
--#  define deflateSetDictionary  z_deflateSetDictionary
--#  define deflateSetHeader      z_deflateSetHeader
--#  define deflateTune           z_deflateTune
--#  define deflate_copyright     z_deflate_copyright
--#  define get_crc_table         z_get_crc_table
--#  ifndef Z_SOLO
--#    define gz_error              z_gz_error
--#    define gz_intmax             z_gz_intmax
--#    define gz_strwinerror        z_gz_strwinerror
--#    define gzbuffer              z_gzbuffer
--#    define gzclearerr            z_gzclearerr
--#    define gzclose               z_gzclose
--#    define gzclose_r             z_gzclose_r
--#    define gzclose_w             z_gzclose_w
--#    define gzdirect              z_gzdirect
--#    define gzdopen               z_gzdopen
--#    define gzeof                 z_gzeof
--#    define gzerror               z_gzerror
--#    define gzflush               z_gzflush
--#    define gzfread               z_gzfread
--#    define gzfwrite              z_gzfwrite
--#    define gzgetc                z_gzgetc
--#    define gzgetc_               z_gzgetc_
--#    define gzgets                z_gzgets
--#    define gzoffset              z_gzoffset
--#    define gzoffset64            z_gzoffset64
--#    define gzopen                z_gzopen
--#    define gzopen64              z_gzopen64
--#    ifdef _WIN32
--#      define gzopen_w              z_gzopen_w
--#    endif
--#    define gzprintf              z_gzprintf
--#    define gzputc                z_gzputc
--#    define gzputs                z_gzputs
--#    define gzread                z_gzread
--#    define gzrewind              z_gzrewind
--#    define gzseek                z_gzseek
--#    define gzseek64              z_gzseek64
--#    define gzsetparams           z_gzsetparams
--#    define gztell                z_gztell
--#    define gztell64              z_gztell64
--#    define gzungetc              z_gzungetc
--#    define gzvprintf             z_gzvprintf
--#    define gzwrite               z_gzwrite
--#  endif
--#  define inflate               z_inflate
--#  define inflateBack           z_inflateBack
--#  define inflateBackEnd        z_inflateBackEnd
--#  define inflateBackInit       z_inflateBackInit
--#  define inflateBackInit_      z_inflateBackInit_
--#  define inflateCodesUsed      z_inflateCodesUsed
--#  define inflateCopy           z_inflateCopy
--#  define inflateEnd            z_inflateEnd
--#  define inflateGetDictionary  z_inflateGetDictionary
--#  define inflateGetHeader      z_inflateGetHeader
--#  define inflateInit           z_inflateInit
--#  define inflateInit2          z_inflateInit2
--#  define inflateInit2_         z_inflateInit2_
--#  define inflateInit_          z_inflateInit_
--#  define inflateMark           z_inflateMark
--#  define inflatePrime          z_inflatePrime
--#  define inflateReset          z_inflateReset
--#  define inflateReset2         z_inflateReset2
--#  define inflateResetKeep      z_inflateResetKeep
--#  define inflateSetDictionary  z_inflateSetDictionary
--#  define inflateSync           z_inflateSync
--#  define inflateSyncPoint      z_inflateSyncPoint
--#  define inflateUndermine      z_inflateUndermine
--#  define inflateValidate       z_inflateValidate
--#  define inflate_copyright     z_inflate_copyright
--#  define inflate_fast          z_inflate_fast
--#  define inflate_table         z_inflate_table
--#  ifndef Z_SOLO
--#    define uncompress            z_uncompress
--#    define uncompress2           z_uncompress2
--#  endif
--#  define zError                z_zError
--#  ifndef Z_SOLO
--#    define zcalloc               z_zcalloc
--#    define zcfree                z_zcfree
--#  endif
--#  define zlibCompileFlags      z_zlibCompileFlags
--#  define zlibVersion           z_zlibVersion
--
--/* all zlib typedefs in zlib.h and zconf.h */
--#  define Byte                  z_Byte
--#  define Bytef                 z_Bytef
--#  define alloc_func            z_alloc_func
--#  define charf                 z_charf
--#  define free_func             z_free_func
--#  ifndef Z_SOLO
--#    define gzFile                z_gzFile
--#  endif
--#  define gz_header             z_gz_header
--#  define gz_headerp            z_gz_headerp
--#  define in_func               z_in_func
--#  define intf                  z_intf
--#  define out_func              z_out_func
--#  define uInt                  z_uInt
--#  define uIntf                 z_uIntf
--#  define uLong                 z_uLong
--#  define uLongf                z_uLongf
--#  define voidp                 z_voidp
--#  define voidpc                z_voidpc
--#  define voidpf                z_voidpf
--
--/* all zlib structs in zlib.h and zconf.h */
--#  define gz_header_s           z_gz_header_s
--#  define internal_state        z_internal_state
--
--#endif
--
--#if defined(__MSDOS__) && !defined(MSDOS)
--#  define MSDOS
--#endif
--#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
--#  define OS2
--#endif
--#if defined(_WINDOWS) && !defined(WINDOWS)
--#  define WINDOWS
--#endif
--#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
--#  ifndef WIN32
--#    define WIN32
--#  endif
--#endif
--#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
--#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
--#    ifndef SYS16BIT
--#      define SYS16BIT
--#    endif
--#  endif
--#endif
--
--/*
-- * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
-- * than 64k bytes at a time (needed on systems with 16-bit int).
-- */
--#ifdef SYS16BIT
--#  define MAXSEG_64K
--#endif
--#ifdef MSDOS
--#  define UNALIGNED_OK
--#endif
--
--#ifdef __STDC_VERSION__
--#  ifndef STDC
--#    define STDC
--#  endif
--#  if __STDC_VERSION__ >= 199901L
--#    ifndef STDC99
--#      define STDC99
--#    endif
--#  endif
--#endif
--#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
--#  define STDC
--#endif
--#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
--#  define STDC
--#endif
--#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
--#  define STDC
--#endif
--#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
--#  define STDC
--#endif
--
--#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
--#  define STDC
--#endif
--
--#ifndef STDC
--#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
--#    define const       /* note: need a more gentle solution here */
--#  endif
--#endif
--
--#if defined(ZLIB_CONST) && !defined(z_const)
--#  define z_const const
--#else
--#  define z_const
--#endif
--
--#ifdef Z_SOLO
--   typedef unsigned long z_size_t;
--#else
--#  define z_longlong long long
--#  if defined(NO_SIZE_T)
--     typedef unsigned NO_SIZE_T z_size_t;
--#  elif defined(STDC)
--#    include <stddef.h>
--     typedef size_t z_size_t;
--#  else
--     typedef unsigned long z_size_t;
--#  endif
--#  undef z_longlong
--#endif
--
--/* Maximum value for memLevel in deflateInit2 */
--#ifndef MAX_MEM_LEVEL
--#  ifdef MAXSEG_64K
--#    define MAX_MEM_LEVEL 8
--#  else
--#    define MAX_MEM_LEVEL 9
--#  endif
--#endif
--
--/* Maximum value for windowBits in deflateInit2 and inflateInit2.
-- * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
-- * created by gzip. (Files created by minigzip can still be extracted by
-- * gzip.)
-- */
--#ifndef MAX_WBITS
--#  define MAX_WBITS   15 /* 32K LZ77 window */
--#endif
--
--/* The memory requirements for deflate are (in bytes):
--            (1 << (windowBits+2)) +  (1 << (memLevel+9))
-- that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
-- plus a few kilobytes for small objects. For example, if you want to reduce
-- the default memory requirements from 256K to 128K, compile with
--     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
-- Of course this will generally degrade compression (there's no free lunch).
--
--   The memory requirements for inflate are (in bytes) 1 << windowBits
-- that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
-- for small objects.
--*/
--
--                        /* Type declarations */
--
--#ifndef OF /* function prototypes */
--#  ifdef STDC
--#    define OF(args)  args
--#  else
--#    define OF(args)  ()
--#  endif
--#endif
--
--#ifndef Z_ARG /* function prototypes for stdarg */
--#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#    define Z_ARG(args)  args
--#  else
--#    define Z_ARG(args)  ()
--#  endif
--#endif
--
--/* The following definitions for FAR are needed only for MSDOS mixed
-- * model programming (small or medium model with some far allocations).
-- * This was tested only with MSC; for other MSDOS compilers you may have
-- * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
-- * just define FAR to be empty.
-- */
--#ifdef SYS16BIT
--#  if defined(M_I86SM) || defined(M_I86MM)
--     /* MSC small or medium model */
--#    define SMALL_MEDIUM
--#    ifdef _MSC_VER
--#      define FAR _far
--#    else
--#      define FAR far
--#    endif
--#  endif
--#  if (defined(__SMALL__) || defined(__MEDIUM__))
--     /* Turbo C small or medium model */
--#    define SMALL_MEDIUM
--#    ifdef __BORLANDC__
--#      define FAR _far
--#    else
--#      define FAR far
--#    endif
--#  endif
--#endif
--
--#if defined(WINDOWS) || defined(WIN32)
--   /* If building or using zlib as a DLL, define ZLIB_DLL.
--    * This is not mandatory, but it offers a little performance increase.
--    */
--#  ifdef ZLIB_DLL
--#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
--#      ifdef ZLIB_INTERNAL
--#        define ZEXTERN extern __declspec(dllexport)
--#      else
--#        define ZEXTERN extern __declspec(dllimport)
--#      endif
--#    endif
--#  endif  /* ZLIB_DLL */
--   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
--    * define ZLIB_WINAPI.
--    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
--    */
--#  ifdef ZLIB_WINAPI
--#    ifdef FAR
--#      undef FAR
--#    endif
--#    include <windows.h>
--     /* No need for _export, use ZLIB.DEF instead. */
--     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
--#    define ZEXPORT WINAPI
--#    ifdef WIN32
--#      define ZEXPORTVA WINAPIV
--#    else
--#      define ZEXPORTVA FAR CDECL
--#    endif
--#  endif
--#endif
--
--#if defined (__BEOS__)
--#  ifdef ZLIB_DLL
--#    ifdef ZLIB_INTERNAL
--#      define ZEXPORT   __declspec(dllexport)
--#      define ZEXPORTVA __declspec(dllexport)
--#    else
--#      define ZEXPORT   __declspec(dllimport)
--#      define ZEXPORTVA __declspec(dllimport)
--#    endif
--#  endif
--#endif
--
--#ifndef ZEXTERN
--#  define ZEXTERN extern
--#endif
--#ifndef ZEXPORT
--#  define ZEXPORT
--#endif
--#ifndef ZEXPORTVA
--#  define ZEXPORTVA
--#endif
--
--#ifndef FAR
--#  define FAR
--#endif
--
--#if !defined(__MACTYPES__)
--typedef unsigned char  Byte;  /* 8 bits */
--#endif
--typedef unsigned int   uInt;  /* 16 bits or more */
--typedef unsigned long  uLong; /* 32 bits or more */
--
--#ifdef SMALL_MEDIUM
--   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
--#  define Bytef Byte FAR
--#else
--   typedef Byte  FAR Bytef;
--#endif
--typedef char  FAR charf;
--typedef int   FAR intf;
--typedef uInt  FAR uIntf;
--typedef uLong FAR uLongf;
--
--#ifdef STDC
--   typedef void const *voidpc;
--   typedef void FAR   *voidpf;
--   typedef void       *voidp;
--#else
--   typedef Byte const *voidpc;
--   typedef Byte FAR   *voidpf;
--   typedef Byte       *voidp;
--#endif
--
--#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
--#  include <limits.h>
--#  if (UINT_MAX == 0xffffffffUL)
--#    define Z_U4 unsigned
--#  elif (ULONG_MAX == 0xffffffffUL)
--#    define Z_U4 unsigned long
--#  elif (USHRT_MAX == 0xffffffffUL)
--#    define Z_U4 unsigned short
--#  endif
--#endif
--
--#ifdef Z_U4
--   typedef Z_U4 z_crc_t;
--#else
--   typedef unsigned long z_crc_t;
--#endif
--
--#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
--#  define Z_HAVE_UNISTD_H
--#endif
--
--#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
--#  define Z_HAVE_STDARG_H
--#endif
--
--#ifdef STDC
--#  ifndef Z_SOLO
--#    include <sys/types.h>      /* for off_t */
--#  endif
--#endif
--
--#if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#  ifndef Z_SOLO
--#    include <stdarg.h>         /* for va_list */
--#  endif
--#endif
--
--#ifdef _WIN32
--#  ifndef Z_SOLO
--#    include <stddef.h>         /* for wchar_t */
--#  endif
--#endif
--
--/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
-- * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
-- * though the former does not conform to the LFS document), but considering
-- * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
-- * equivalently requesting no 64-bit operations
-- */
--#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
--#  undef _LARGEFILE64_SOURCE
--#endif
--
--#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
--#  define Z_HAVE_UNISTD_H
--#endif
--#ifndef Z_SOLO
--#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
--#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
--#    ifdef VMS
--#      include <unixio.h>       /* for off_t */
--#    endif
--#    ifndef z_off_t
--#      define z_off_t off_t
--#    endif
--#  endif
--#endif
--
--#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
--#  define Z_LFS64
--#endif
--
--#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
--#  define Z_LARGE64
--#endif
--
--#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
--#  define Z_WANT64
--#endif
--
--#if !defined(SEEK_SET) && !defined(Z_SOLO)
--#  define SEEK_SET        0       /* Seek from beginning of file.  */
--#  define SEEK_CUR        1       /* Seek from current position.  */
--#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
--#endif
--
--#ifndef z_off_t
--#  define z_off_t long
--#endif
--
--#if !defined(_WIN32) && defined(Z_LARGE64)
--#  define z_off64_t off64_t
--#else
--#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
--#    define z_off64_t __int64
--#  else
--#    define z_off64_t z_off_t
--#  endif
--#endif
--
--/* MVS linker does not support external names larger than 8 bytes */
--#if defined(__MVS__)
--  #pragma map(deflateInit_,"DEIN")
--  #pragma map(deflateInit2_,"DEIN2")
--  #pragma map(deflateEnd,"DEEND")
--  #pragma map(deflateBound,"DEBND")
--  #pragma map(inflateInit_,"ININ")
--  #pragma map(inflateInit2_,"ININ2")
--  #pragma map(inflateEnd,"INEND")
--  #pragma map(inflateSync,"INSY")
--  #pragma map(inflateSetDictionary,"INSEDI")
--  #pragma map(compressBound,"CMBND")
--  #pragma map(inflate_table,"INTABL")
--  #pragma map(inflate_fast,"INFA")
--  #pragma map(inflate_copyright,"INCOPY")
--#endif
--
--#endif /* ZCONF_H */
diff --cc zlib/zlib.3
index bda4eb0737090cdd305057540892cb6a212d9dc9,bda4eb0737090cdd305057540892cb6a212d9dc9..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,149 -1,149 +1,0 @@@
--.TH ZLIB 3 "15 Jan 2017"
--.SH NAME
--zlib \- compression/decompression library
--.SH SYNOPSIS
--[see
--.I zlib.h
--for full description]
--.SH DESCRIPTION
--The
--.I zlib
--library is a general purpose data compression library.
--The code is thread safe, assuming that the standard library functions
--used are thread safe, such as memory allocation routines.
--It provides in-memory compression and decompression functions,
--including integrity checks of the uncompressed data.
--This version of the library supports only one compression method (deflation)
--but other algorithms may be added later
--with the same stream interface.
--.LP
--Compression can be done in a single step if the buffers are large enough
--or can be done by repeated calls of the compression function.
--In the latter case,
--the application must provide more input and/or consume the output
--(providing more output space) before each call.
--.LP
--The library also supports reading and writing files in
--.IR gzip (1)
--(.gz) format
--with an interface similar to that of stdio.
--.LP
--The library does not install any signal handler.
--The decoder checks the consistency of the compressed data,
--so the library should never crash even in the case of corrupted input.
--.LP
--All functions of the compression library are documented in the file
--.IR zlib.h .
--The distribution source includes examples of use of the library
--in the files
--.I test/example.c
--and
--.IR test/minigzip.c,
--as well as other examples in the
--.IR examples/
--directory.
--.LP
--Changes to this version are documented in the file
--.I ChangeLog
--that accompanies the source.
--.LP
--.I zlib
--is built in to many languages and operating systems, including but not limited to
--Java, Python, .NET, PHP, Perl, Ruby, Swift, and Go.
--.LP
--An experimental package to read and write files in the .zip format,
--written on top of
--.I zlib
--by Gilles Vollant (info@winimage.com),
--is available at:
--.IP
--http://www.winimage.com/zLibDll/minizip.html
--and also in the
--.I contrib/minizip
--directory of the main
--.I zlib
--source distribution.
--.SH "SEE ALSO"
--The
--.I zlib
--web site can be found at:
--.IP
--http://zlib.net/
--.LP
--The data format used by the
--.I zlib
--library is described by RFC
--(Request for Comments) 1950 to 1952 in the files:
--.IP
--http://tools.ietf.org/html/rfc1950 (for the zlib header and trailer format)
--.br
--http://tools.ietf.org/html/rfc1951 (for the deflate compressed data format)
--.br
--http://tools.ietf.org/html/rfc1952 (for the gzip header and trailer format)
--.LP
--Mark Nelson wrote an article about
--.I zlib
--for the Jan. 1997 issue of  Dr. Dobb's Journal;
--a copy of the article is available at:
--.IP
--http://marknelson.us/1997/01/01/zlib-engine/
--.SH "REPORTING PROBLEMS"
--Before reporting a problem,
--please check the
--.I zlib
--web site to verify that you have the latest version of
--.IR zlib ;
--otherwise,
--obtain the latest version and see if the problem still exists.
--Please read the
--.I zlib
--FAQ at:
--.IP
--http://zlib.net/zlib_faq.html
--.LP
--before asking for help.
--Send questions and/or comments to zlib@gzip.org,
--or (for the Windows DLL version) to Gilles Vollant (info@winimage.com).
--.SH AUTHORS AND LICENSE
--Version 1.2.11
--.LP
--Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
--.LP
--This software is provided 'as-is', without any express or implied
--warranty.  In no event will the authors be held liable for any damages
--arising from the use of this software.
--.LP
--Permission is granted to anyone to use this software for any purpose,
--including commercial applications, and to alter it and redistribute it
--freely, subject to the following restrictions:
--.LP
--.nr step 1 1
--.IP \n[step]. 3
--The origin of this software must not be misrepresented; you must not
--claim that you wrote the original software. If you use this software
--in a product, an acknowledgment in the product documentation would be
--appreciated but is not required.
--.IP \n+[step].
--Altered source versions must be plainly marked as such, and must not be
--misrepresented as being the original software.
--.IP \n+[step].
--This notice may not be removed or altered from any source distribution.
--.LP
--Jean-loup Gailly        Mark Adler
--.br
--jloup@gzip.org          madler@alumni.caltech.edu
--.LP
--The deflate format used by
--.I zlib
--was defined by Phil Katz.
--The deflate and
--.I zlib
--specifications were written by L. Peter Deutsch.
--Thanks to all the people who reported problems and suggested various
--improvements in
--.IR zlib ;
--who are too numerous to cite here.
--.LP
--UNIX manual page by R. P. C. Rodgers,
--U.S. National Library of Medicine (rodgers@nlm.nih.gov).
--.\" end of man page
diff --cc zlib/zlib.h
index f09cdaf1e0543de911d8220befdb51fa8632a9e6,f09cdaf1e0543de911d8220befdb51fa8632a9e6..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,1912 -1,1912 +1,0 @@@
--/* zlib.h -- interface of the 'zlib' general purpose compression library
--  version 1.2.11, January 15th, 2017
--
--  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
--
--  This software is provided 'as-is', without any express or implied
--  warranty.  In no event will the authors be held liable for any damages
--  arising from the use of this software.
--
--  Permission is granted to anyone to use this software for any purpose,
--  including commercial applications, and to alter it and redistribute it
--  freely, subject to the following restrictions:
--
--  1. The origin of this software must not be misrepresented; you must not
--     claim that you wrote the original software. If you use this software
--     in a product, an acknowledgment in the product documentation would be
--     appreciated but is not required.
--  2. Altered source versions must be plainly marked as such, and must not be
--     misrepresented as being the original software.
--  3. This notice may not be removed or altered from any source distribution.
--
--  Jean-loup Gailly        Mark Adler
--  jloup@gzip.org          madler@alumni.caltech.edu
--
--
--  The data format used by the zlib library is described by RFCs (Request for
--  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
--  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
--*/
--
--#ifndef ZLIB_H
--#define ZLIB_H
--
--#include "zconf.h"
--
--#ifdef __cplusplus
--extern "C" {
--#endif
--
--#define ZLIB_VERSION "1.2.11"
--#define ZLIB_VERNUM 0x12b0
--#define ZLIB_VER_MAJOR 1
--#define ZLIB_VER_MINOR 2
--#define ZLIB_VER_REVISION 11
--#define ZLIB_VER_SUBREVISION 0
--
--/*
--    The 'zlib' compression library provides in-memory compression and
--  decompression functions, including integrity checks of the uncompressed data.
--  This version of the library supports only one compression method (deflation)
--  but other algorithms will be added later and will have the same stream
--  interface.
--
--    Compression can be done in a single step if the buffers are large enough,
--  or can be done by repeated calls of the compression function.  In the latter
--  case, the application must provide more input and/or consume the output
--  (providing more output space) before each call.
--
--    The compressed data format used by default by the in-memory functions is
--  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
--  around a deflate stream, which is itself documented in RFC 1951.
--
--    The library also supports reading and writing files in gzip (.gz) format
--  with an interface similar to that of stdio using the functions that start
--  with "gz".  The gzip format is different from the zlib format.  gzip is a
--  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
--
--    This library can optionally read and write gzip and raw deflate streams in
--  memory as well.
--
--    The zlib format was designed to be compact and fast for use in memory
--  and on communications channels.  The gzip format was designed for single-
--  file compression on file systems, has a larger header than zlib to maintain
--  directory information, and uses a different, slower check method than zlib.
--
--    The library does not install any signal handler.  The decoder checks
--  the consistency of the compressed data, so the library should never crash
--  even in the case of corrupted input.
--*/
--
--typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
--typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
--
--struct internal_state;
--
--typedef struct z_stream_s {
--    z_const Bytef *next_in;     /* next input byte */
--    uInt     avail_in;  /* number of bytes available at next_in */
--    uLong    total_in;  /* total number of input bytes read so far */
--
--    Bytef    *next_out; /* next output byte will go here */
--    uInt     avail_out; /* remaining free space at next_out */
--    uLong    total_out; /* total number of bytes output so far */
--
--    z_const char *msg;  /* last error message, NULL if no error */
--    struct internal_state FAR *state; /* not visible by applications */
--
--    alloc_func zalloc;  /* used to allocate the internal state */
--    free_func  zfree;   /* used to free the internal state */
--    voidpf     opaque;  /* private data object passed to zalloc and zfree */
--
--    int     data_type;  /* best guess about the data type: binary or text
--                           for deflate, or the decoding state for inflate */
--    uLong   adler;      /* Adler-32 or CRC-32 value of the uncompressed data */
--    uLong   reserved;   /* reserved for future use */
--} z_stream;
--
--typedef z_stream FAR *z_streamp;
--
--/*
--     gzip header information passed to and from zlib routines.  See RFC 1952
--  for more details on the meanings of these fields.
--*/
--typedef struct gz_header_s {
--    int     text;       /* true if compressed data believed to be text */
--    uLong   time;       /* modification time */
--    int     xflags;     /* extra flags (not used when writing a gzip file) */
--    int     os;         /* operating system */
--    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
--    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
--    uInt    extra_max;  /* space at extra (only when reading header) */
--    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
--    uInt    name_max;   /* space at name (only when reading header) */
--    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
--    uInt    comm_max;   /* space at comment (only when reading header) */
--    int     hcrc;       /* true if there was or will be a header crc */
--    int     done;       /* true when done reading gzip header (not used
--                           when writing a gzip file) */
--} gz_header;
--
--typedef gz_header FAR *gz_headerp;
--
--/*
--     The application must update next_in and avail_in when avail_in has dropped
--   to zero.  It must update next_out and avail_out when avail_out has dropped
--   to zero.  The application must initialize zalloc, zfree and opaque before
--   calling the init function.  All other fields are set by the compression
--   library and must not be updated by the application.
--
--     The opaque value provided by the application will be passed as the first
--   parameter for calls of zalloc and zfree.  This can be useful for custom
--   memory management.  The compression library attaches no meaning to the
--   opaque value.
--
--     zalloc must return Z_NULL if there is not enough memory for the object.
--   If zlib is used in a multi-threaded application, zalloc and zfree must be
--   thread safe.  In that case, zlib is thread-safe.  When zalloc and zfree are
--   Z_NULL on entry to the initialization function, they are set to internal
--   routines that use the standard library functions malloc() and free().
--
--     On 16-bit systems, the functions zalloc and zfree must be able to allocate
--   exactly 65536 bytes, but will not be required to allocate more than this if
--   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
--   returned by zalloc for objects of exactly 65536 bytes *must* have their
--   offset normalized to zero.  The default allocation function provided by this
--   library ensures this (see zutil.c).  To reduce memory requirements and avoid
--   any allocation of 64K objects, at the expense of compression ratio, compile
--   the library with -DMAX_WBITS=14 (see zconf.h).
--
--     The fields total_in and total_out can be used for statistics or progress
--   reports.  After compression, total_in holds the total size of the
--   uncompressed data and may be saved for use by the decompressor (particularly
--   if the decompressor wants to decompress everything in a single step).
--*/
--
--                        /* constants */
--
--#define Z_NO_FLUSH      0
--#define Z_PARTIAL_FLUSH 1
--#define Z_SYNC_FLUSH    2
--#define Z_FULL_FLUSH    3
--#define Z_FINISH        4
--#define Z_BLOCK         5
--#define Z_TREES         6
--/* Allowed flush values; see deflate() and inflate() below for details */
--
--#define Z_OK            0
--#define Z_STREAM_END    1
--#define Z_NEED_DICT     2
--#define Z_ERRNO        (-1)
--#define Z_STREAM_ERROR (-2)
--#define Z_DATA_ERROR   (-3)
--#define Z_MEM_ERROR    (-4)
--#define Z_BUF_ERROR    (-5)
--#define Z_VERSION_ERROR (-6)
--/* Return codes for the compression/decompression functions. Negative values
-- * are errors, positive values are used for special but normal events.
-- */
--
--#define Z_NO_COMPRESSION         0
--#define Z_BEST_SPEED             1
--#define Z_BEST_COMPRESSION       9
--#define Z_DEFAULT_COMPRESSION  (-1)
--/* compression levels */
--
--#define Z_FILTERED            1
--#define Z_HUFFMAN_ONLY        2
--#define Z_RLE                 3
--#define Z_FIXED               4
--#define Z_DEFAULT_STRATEGY    0
--/* compression strategy; see deflateInit2() below for details */
--
--#define Z_BINARY   0
--#define Z_TEXT     1
--#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
--#define Z_UNKNOWN  2
--/* Possible values of the data_type field for deflate() */
--
--#define Z_DEFLATED   8
--/* The deflate compression method (the only one supported in this version) */
--
--#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
--
--#define zlib_version zlibVersion()
--/* for compatibility with versions < 1.0.2 */
--
--
--                        /* basic functions */
--
--ZEXTERN const char * ZEXPORT zlibVersion OF((void));
--/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
--   If the first character differs, the library code actually used is not
--   compatible with the zlib.h header file used by the application.  This check
--   is automatically made by deflateInit and inflateInit.
-- */
--
--/*
--ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
--
--     Initializes the internal stream state for compression.  The fields
--   zalloc, zfree and opaque must be initialized before by the caller.  If
--   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
--   allocation functions.
--
--     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
--   1 gives best speed, 9 gives best compression, 0 gives no compression at all
--   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
--   requests a default compromise between speed and compression (currently
--   equivalent to level 6).
--
--     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_STREAM_ERROR if level is not a valid compression level, or
--   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
--   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
--   if there is no error message.  deflateInit does not perform any compression:
--   this will be done by deflate().
--*/
--
--
--ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
--/*
--    deflate compresses as much data as possible, and stops when the input
--  buffer becomes empty or the output buffer becomes full.  It may introduce
--  some output latency (reading input without producing any output) except when
--  forced to flush.
--
--    The detailed semantics are as follows.  deflate performs one or both of the
--  following actions:
--
--  - Compress more input starting at next_in and update next_in and avail_in
--    accordingly.  If not all input can be processed (because there is not
--    enough room in the output buffer), next_in and avail_in are updated and
--    processing will resume at this point for the next call of deflate().
--
--  - Generate more output starting at next_out and update next_out and avail_out
--    accordingly.  This action is forced if the parameter flush is non zero.
--    Forcing flush frequently degrades the compression ratio, so this parameter
--    should be set only when necessary.  Some output may be provided even if
--    flush is zero.
--
--    Before the call of deflate(), the application should ensure that at least
--  one of the actions is possible, by providing more input and/or consuming more
--  output, and updating avail_in or avail_out accordingly; avail_out should
--  never be zero before the call.  The application can consume the compressed
--  output when it wants, for example when the output buffer is full (avail_out
--  == 0), or after each call of deflate().  If deflate returns Z_OK and with
--  zero avail_out, it must be called again after making room in the output
--  buffer because there might be more output pending. See deflatePending(),
--  which can be used if desired to determine whether or not there is more ouput
--  in that case.
--
--    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
--  decide how much data to accumulate before producing output, in order to
--  maximize compression.
--
--    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
--  flushed to the output buffer and the output is aligned on a byte boundary, so
--  that the decompressor can get all input data available so far.  (In
--  particular avail_in is zero after the call if enough output space has been
--  provided before the call.) Flushing may degrade compression for some
--  compression algorithms and so it should be used only when necessary.  This
--  completes the current deflate block and follows it with an empty stored block
--  that is three bits plus filler bits to the next byte, followed by four bytes
--  (00 00 ff ff).
--
--    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
--  output buffer, but the output is not aligned to a byte boundary.  All of the
--  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
--  This completes the current deflate block and follows it with an empty fixed
--  codes block that is 10 bits long.  This assures that enough bytes are output
--  in order for the decompressor to finish the block before the empty fixed
--  codes block.
--
--    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
--  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
--  seven bits of the current block are held to be written as the next byte after
--  the next deflate block is completed.  In this case, the decompressor may not
--  be provided enough bits at this point in order to complete decompression of
--  the data provided so far to the compressor.  It may need to wait for the next
--  block to be emitted.  This is for advanced applications that need to control
--  the emission of deflate blocks.
--
--    If flush is set to Z_FULL_FLUSH, all output is flushed as with
--  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
--  restart from this point if previous compressed data has been damaged or if
--  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
--  compression.
--
--    If deflate returns with avail_out == 0, this function must be called again
--  with the same value of the flush parameter and more output space (updated
--  avail_out), until the flush is complete (deflate returns with non-zero
--  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
--  avail_out is greater than six to avoid repeated flush markers due to
--  avail_out == 0 on return.
--
--    If the parameter flush is set to Z_FINISH, pending input is processed,
--  pending output is flushed and deflate returns with Z_STREAM_END if there was
--  enough output space.  If deflate returns with Z_OK or Z_BUF_ERROR, this
--  function must be called again with Z_FINISH and more output space (updated
--  avail_out) but no more input data, until it returns with Z_STREAM_END or an
--  error.  After deflate has returned Z_STREAM_END, the only possible operations
--  on the stream are deflateReset or deflateEnd.
--
--    Z_FINISH can be used in the first deflate call after deflateInit if all the
--  compression is to be done in a single step.  In order to complete in one
--  call, avail_out must be at least the value returned by deflateBound (see
--  below).  Then deflate is guaranteed to return Z_STREAM_END.  If not enough
--  output space is provided, deflate will not return Z_STREAM_END, and it must
--  be called again as described above.
--
--    deflate() sets strm->adler to the Adler-32 checksum of all input read
--  so far (that is, total_in bytes).  If a gzip stream is being generated, then
--  strm->adler will be the CRC-32 checksum of the input read so far.  (See
--  deflateInit2 below.)
--
--    deflate() may update strm->data_type if it can make a good guess about
--  the input data type (Z_BINARY or Z_TEXT).  If in doubt, the data is
--  considered binary.  This field is only for information purposes and does not
--  affect the compression algorithm in any manner.
--
--    deflate() returns Z_OK if some progress has been made (more input
--  processed or more output produced), Z_STREAM_END if all input has been
--  consumed and all output has been produced (only when flush is set to
--  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
--  if next_in or next_out was Z_NULL or the state was inadvertently written over
--  by the application), or Z_BUF_ERROR if no progress is possible (for example
--  avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not fatal, and
--  deflate() can be called again with more input and more output space to
--  continue compressing.
--*/
--
--
--ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
--/*
--     All dynamically allocated data structures for this stream are freed.
--   This function discards any unprocessed input and does not flush any pending
--   output.
--
--     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
--   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
--   prematurely (some input or output was discarded).  In the error case, msg
--   may be set but then points to a static string (which must not be
--   deallocated).
--*/
--
--
--/*
--ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
--
--     Initializes the internal stream state for decompression.  The fields
--   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
--   the caller.  In the current version of inflate, the provided input is not
--   read or consumed.  The allocation of a sliding window will be deferred to
--   the first call of inflate (if the decompression does not complete on the
--   first call).  If zalloc and zfree are set to Z_NULL, inflateInit updates
--   them to use default allocation functions.
--
--     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
--   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
--   invalid, such as a null pointer to the structure.  msg is set to null if
--   there is no error message.  inflateInit does not perform any decompression.
--   Actual decompression will be done by inflate().  So next_in, and avail_in,
--   next_out, and avail_out are unused and unchanged.  The current
--   implementation of inflateInit() does not process any header information --
--   that is deferred until inflate() is called.
--*/
--
--
--ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
--/*
--    inflate decompresses as much data as possible, and stops when the input
--  buffer becomes empty or the output buffer becomes full.  It may introduce
--  some output latency (reading input without producing any output) except when
--  forced to flush.
--
--  The detailed semantics are as follows.  inflate performs one or both of the
--  following actions:
--
--  - Decompress more input starting at next_in and update next_in and avail_in
--    accordingly.  If not all input can be processed (because there is not
--    enough room in the output buffer), then next_in and avail_in are updated
--    accordingly, and processing will resume at this point for the next call of
--    inflate().
--
--  - Generate more output starting at next_out and update next_out and avail_out
--    accordingly.  inflate() provides as much output as possible, until there is
--    no more input data or no more space in the output buffer (see below about
--    the flush parameter).
--
--    Before the call of inflate(), the application should ensure that at least
--  one of the actions is possible, by providing more input and/or consuming more
--  output, and updating the next_* and avail_* values accordingly.  If the
--  caller of inflate() does not provide both available input and available
--  output space, it is possible that there will be no progress made.  The
--  application can consume the uncompressed output when it wants, for example
--  when the output buffer is full (avail_out == 0), or after each call of
--  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
--  called again after making room in the output buffer because there might be
--  more output pending.
--
--    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
--  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
--  output as possible to the output buffer.  Z_BLOCK requests that inflate()
--  stop if and when it gets to the next deflate block boundary.  When decoding
--  the zlib or gzip format, this will cause inflate() to return immediately
--  after the header and before the first block.  When doing a raw inflate,
--  inflate() will go ahead and process the first block, and will return when it
--  gets to the end of that block, or when it runs out of data.
--
--    The Z_BLOCK option assists in appending to or combining deflate streams.
--  To assist in this, on return inflate() always sets strm->data_type to the
--  number of unused bits in the last byte taken from strm->next_in, plus 64 if
--  inflate() is currently decoding the last block in the deflate stream, plus
--  128 if inflate() returned immediately after decoding an end-of-block code or
--  decoding the complete header up to just before the first byte of the deflate
--  stream.  The end-of-block will not be indicated until all of the uncompressed
--  data from that block has been written to strm->next_out.  The number of
--  unused bits may in general be greater than seven, except when bit 7 of
--  data_type is set, in which case the number of unused bits will be less than
--  eight.  data_type is set as noted here every time inflate() returns for all
--  flush options, and so can be used to determine the amount of currently
--  consumed input in bits.
--
--    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
--  end of each deflate block header is reached, before any actual data in that
--  block is decoded.  This allows the caller to determine the length of the
--  deflate block header for later use in random access within a deflate block.
--  256 is added to the value of strm->data_type when inflate() returns
--  immediately after reaching the end of the deflate block header.
--
--    inflate() should normally be called until it returns Z_STREAM_END or an
--  error.  However if all decompression is to be performed in a single step (a
--  single call of inflate), the parameter flush should be set to Z_FINISH.  In
--  this case all pending input is processed and all pending output is flushed;
--  avail_out must be large enough to hold all of the uncompressed data for the
--  operation to complete.  (The size of the uncompressed data may have been
--  saved by the compressor for this purpose.)  The use of Z_FINISH is not
--  required to perform an inflation in one step.  However it may be used to
--  inform inflate that a faster approach can be used for the single inflate()
--  call.  Z_FINISH also informs inflate to not maintain a sliding window if the
--  stream completes, which reduces inflate's memory footprint.  If the stream
--  does not complete, either because not all of the stream is provided or not
--  enough output space is provided, then a sliding window will be allocated and
--  inflate() can be called again to continue the operation as if Z_NO_FLUSH had
--  been used.
--
--     In this implementation, inflate() always flushes as much output as
--  possible to the output buffer, and always uses the faster approach on the
--  first call.  So the effects of the flush parameter in this implementation are
--  on the return value of inflate() as noted below, when inflate() returns early
--  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
--  memory for a sliding window when Z_FINISH is used.
--
--     If a preset dictionary is needed after this call (see inflateSetDictionary
--  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
--  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
--  strm->adler to the Adler-32 checksum of all output produced so far (that is,
--  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
--  below.  At the end of the stream, inflate() checks that its computed Adler-32
--  checksum is equal to that saved by the compressor and returns Z_STREAM_END
--  only if the checksum is correct.
--
--    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
--  deflate data.  The header type is detected automatically, if requested when
--  initializing with inflateInit2().  Any information contained in the gzip
--  header is not retained unless inflateGetHeader() is used.  When processing
--  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
--  produced so far.  The CRC-32 is checked against the gzip trailer, as is the
--  uncompressed length, modulo 2^32.
--
--    inflate() returns Z_OK if some progress has been made (more input processed
--  or more output produced), Z_STREAM_END if the end of the compressed data has
--  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
--  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
--  corrupted (input stream not conforming to the zlib format or incorrect check
--  value, in which case strm->msg points to a string with a more specific
--  error), Z_STREAM_ERROR if the stream structure was inconsistent (for example
--  next_in or next_out was Z_NULL, or the state was inadvertently written over
--  by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR
--  if no progress was possible or if there was not enough room in the output
--  buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
--  inflate() can be called again with more input and more output space to
--  continue decompressing.  If Z_DATA_ERROR is returned, the application may
--  then call inflateSync() to look for a good compression block if a partial
--  recovery of the data is to be attempted.
--*/
--
--
--ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
--/*
--     All dynamically allocated data structures for this stream are freed.
--   This function discards any unprocessed input and does not flush any pending
--   output.
--
--     inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state
--   was inconsistent.
--*/
--
--
--                        /* Advanced functions */
--
--/*
--    The following functions are needed only in some special applications.
--*/
--
--/*
--ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
--                                     int  level,
--                                     int  method,
--                                     int  windowBits,
--                                     int  memLevel,
--                                     int  strategy));
--
--     This is another version of deflateInit with more compression options.  The
--   fields next_in, zalloc, zfree and opaque must be initialized before by the
--   caller.
--
--     The method parameter is the compression method.  It must be Z_DEFLATED in
--   this version of the library.
--
--     The windowBits parameter is the base two logarithm of the window size
--   (the size of the history buffer).  It should be in the range 8..15 for this
--   version of the library.  Larger values of this parameter result in better
--   compression at the expense of memory usage.  The default value is 15 if
--   deflateInit is used instead.
--
--     For the current implementation of deflate(), a windowBits value of 8 (a
--   window size of 256 bytes) is not supported.  As a result, a request for 8
--   will result in 9 (a 512-byte window).  In that case, providing 8 to
--   inflateInit2() will result in an error when the zlib header with 9 is
--   checked against the initialization of inflate().  The remedy is to not use 8
--   with deflateInit2() with this initialization, or at least in that case use 9
--   with inflateInit2().
--
--     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
--   determines the window size.  deflate() will then generate raw deflate data
--   with no zlib header or trailer, and will not compute a check value.
--
--     windowBits can also be greater than 15 for optional gzip encoding.  Add
--   16 to windowBits to write a simple gzip header and trailer around the
--   compressed data instead of a zlib wrapper.  The gzip header will have no
--   file name, no extra data, no comment, no modification time (set to zero), no
--   header crc, and the operating system will be set to the appropriate value,
--   if the operating system was determined at compile time.  If a gzip stream is
--   being written, strm->adler is a CRC-32 instead of an Adler-32.
--
--     For raw deflate or gzip encoding, a request for a 256-byte window is
--   rejected as invalid, since only the zlib header provides a means of
--   transmitting the window size to the decompressor.
--
--     The memLevel parameter specifies how much memory should be allocated
--   for the internal compression state.  memLevel=1 uses minimum memory but is
--   slow and reduces compression ratio; memLevel=9 uses maximum memory for
--   optimal speed.  The default value is 8.  See zconf.h for total memory usage
--   as a function of windowBits and memLevel.
--
--     The strategy parameter is used to tune the compression algorithm.  Use the
--   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
--   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
--   string match), or Z_RLE to limit match distances to one (run-length
--   encoding).  Filtered data consists mostly of small values with a somewhat
--   random distribution.  In this case, the compression algorithm is tuned to
--   compress them better.  The effect of Z_FILTERED is to force more Huffman
--   coding and less string matching; it is somewhat intermediate between
--   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
--   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
--   strategy parameter only affects the compression ratio but not the
--   correctness of the compressed output even if it is not set appropriately.
--   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
--   decoder for special applications.
--
--     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
--   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
--   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
--   set to null if there is no error message.  deflateInit2 does not perform any
--   compression: this will be done by deflate().
--*/
--
--ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
--                                             const Bytef *dictionary,
--                                             uInt  dictLength));
--/*
--     Initializes the compression dictionary from the given byte sequence
--   without producing any compressed output.  When using the zlib format, this
--   function must be called immediately after deflateInit, deflateInit2 or
--   deflateReset, and before any call of deflate.  When doing raw deflate, this
--   function must be called either before any call of deflate, or immediately
--   after the completion of a deflate block, i.e. after all input has been
--   consumed and all output has been delivered when using any of the flush
--   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The
--   compressor and decompressor must use exactly the same dictionary (see
--   inflateSetDictionary).
--
--     The dictionary should consist of strings (byte sequences) that are likely
--   to be encountered later in the data to be compressed, with the most commonly
--   used strings preferably put towards the end of the dictionary.  Using a
--   dictionary is most useful when the data to be compressed is short and can be
--   predicted with good accuracy; the data can then be compressed better than
--   with the default empty dictionary.
--
--     Depending on the size of the compression data structures selected by
--   deflateInit or deflateInit2, a part of the dictionary may in effect be
--   discarded, for example if the dictionary is larger than the window size
--   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
--   useful should be put at the end of the dictionary, not at the front.  In
--   addition, the current implementation of deflate will use at most the window
--   size minus 262 bytes of the provided dictionary.
--
--     Upon return of this function, strm->adler is set to the Adler-32 value
--   of the dictionary; the decompressor may later use this value to determine
--   which dictionary has been used by the compressor.  (The Adler-32 value
--   applies to the whole dictionary even if only a subset of the dictionary is
--   actually used by the compressor.) If a raw deflate was requested, then the
--   Adler-32 value is not computed and strm->adler is not set.
--
--     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
--   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
--   inconsistent (for example if deflate has already been called for this stream
--   or if not at a block boundary for raw deflate).  deflateSetDictionary does
--   not perform any compression: this will be done by deflate().
--*/
--
--ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm,
--                                             Bytef *dictionary,
--                                             uInt  *dictLength));
--/*
--     Returns the sliding dictionary being maintained by deflate.  dictLength is
--   set to the number of bytes in the dictionary, and that many bytes are copied
--   to dictionary.  dictionary must have enough space, where 32768 bytes is
--   always enough.  If deflateGetDictionary() is called with dictionary equal to
--   Z_NULL, then only the dictionary length is returned, and nothing is copied.
--   Similary, if dictLength is Z_NULL, then it is not set.
--
--     deflateGetDictionary() may return a length less than the window size, even
--   when more than the window size in input has been provided. It may return up
--   to 258 bytes less in that case, due to how zlib's implementation of deflate
--   manages the sliding window and lookahead for matches, where matches can be
--   up to 258 bytes long. If the application needs the last window-size bytes of
--   input, then that would need to be saved by the application outside of zlib.
--
--     deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
--   stream state is inconsistent.
--*/
--
--ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
--                                    z_streamp source));
--/*
--     Sets the destination stream as a complete copy of the source stream.
--
--     This function can be useful when several compression strategies will be
--   tried, for example when there are several ways of pre-processing the input
--   data with a filter.  The streams that will be discarded should then be freed
--   by calling deflateEnd.  Note that deflateCopy duplicates the internal
--   compression state which can be quite large, so this strategy is slow and can
--   consume lots of memory.
--
--     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
--   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
--   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
--   destination.
--*/
--
--ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
--/*
--     This function is equivalent to deflateEnd followed by deflateInit, but
--   does not free and reallocate the internal compression state.  The stream
--   will leave the compression level and any other attributes that may have been
--   set unchanged.
--
--     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent (such as zalloc or state being Z_NULL).
--*/
--
--ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
--                                      int level,
--                                      int strategy));
--/*
--     Dynamically update the compression level and compression strategy.  The
--   interpretation of level and strategy is as in deflateInit2().  This can be
--   used to switch between compression and straight copy of the input data, or
--   to switch to a different kind of input data requiring a different strategy.
--   If the compression approach (which is a function of the level) or the
--   strategy is changed, and if any input has been consumed in a previous
--   deflate() call, then the input available so far is compressed with the old
--   level and strategy using deflate(strm, Z_BLOCK).  There are three approaches
--   for the compression levels 0, 1..3, and 4..9 respectively.  The new level
--   and strategy will take effect at the next call of deflate().
--
--     If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does
--   not have enough output space to complete, then the parameter change will not
--   take effect.  In this case, deflateParams() can be called again with the
--   same parameters and more output space to try again.
--
--     In order to assure a change in the parameters on the first try, the
--   deflate stream should be flushed using deflate() with Z_BLOCK or other flush
--   request until strm.avail_out is not zero, before calling deflateParams().
--   Then no more input data should be provided before the deflateParams() call.
--   If this is done, the old level and strategy will be applied to the data
--   compressed before deflateParams(), and the new level and strategy will be
--   applied to the the data compressed after deflateParams().
--
--     deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream
--   state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if
--   there was not enough output space to complete the compression of the
--   available input data before a change in the strategy or approach.  Note that
--   in the case of a Z_BUF_ERROR, the parameters are not changed.  A return
--   value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be
--   retried with more output space.
--*/
--
--ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
--                                    int good_length,
--                                    int max_lazy,
--                                    int nice_length,
--                                    int max_chain));
--/*
--     Fine tune deflate's internal compression parameters.  This should only be
--   used by someone who understands the algorithm used by zlib's deflate for
--   searching for the best matching string, and even then only by the most
--   fanatic optimizer trying to squeeze out the last compressed bit for their
--   specific input data.  Read the deflate.c source code for the meaning of the
--   max_lazy, good_length, nice_length, and max_chain parameters.
--
--     deflateTune() can be called after deflateInit() or deflateInit2(), and
--   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
-- */
--
--ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
--                                       uLong sourceLen));
--/*
--     deflateBound() returns an upper bound on the compressed size after
--   deflation of sourceLen bytes.  It must be called after deflateInit() or
--   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
--   to allocate an output buffer for deflation in a single pass, and so would be
--   called before deflate().  If that first deflate() call is provided the
--   sourceLen input bytes, an output buffer allocated to the size returned by
--   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
--   to return Z_STREAM_END.  Note that it is possible for the compressed size to
--   be larger than the value returned by deflateBound() if flush options other
--   than Z_FINISH or Z_NO_FLUSH are used.
--*/
--
--ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,
--                                       unsigned *pending,
--                                       int *bits));
--/*
--     deflatePending() returns the number of bytes and bits of output that have
--   been generated, but not yet provided in the available output.  The bytes not
--   provided would be due to the available output space having being consumed.
--   The number of bits of output not provided are between 0 and 7, where they
--   await more bits to join them in order to fill out a full byte.  If pending
--   or bits are Z_NULL, then those values are not set.
--
--     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent.
-- */
--
--ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
--                                     int bits,
--                                     int value));
--/*
--     deflatePrime() inserts bits in the deflate output stream.  The intent
--   is that this function is used to start off the deflate output with the bits
--   leftover from a previous deflate stream when appending to it.  As such, this
--   function can only be used for raw deflate, and must be used before the first
--   deflate() call after a deflateInit2() or deflateReset().  bits must be less
--   than or equal to 16, and that many of the least significant bits of value
--   will be inserted in the output.
--
--     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
--   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
--   source stream state was inconsistent.
--*/
--
--ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
--                                         gz_headerp head));
--/*
--     deflateSetHeader() provides gzip header information for when a gzip
--   stream is requested by deflateInit2().  deflateSetHeader() may be called
--   after deflateInit2() or deflateReset() and before the first call of
--   deflate().  The text, time, os, extra field, name, and comment information
--   in the provided gz_header structure are written to the gzip header (xflag is
--   ignored -- the extra flags are set according to the compression level).  The
--   caller must assure that, if not Z_NULL, name and comment are terminated with
--   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
--   available there.  If hcrc is true, a gzip header crc is included.  Note that
--   the current versions of the command-line version of gzip (up through version
--   1.3.x) do not support header crc's, and will report that it is a "multi-part
--   gzip file" and give up.
--
--     If deflateSetHeader is not used, the default gzip header has text false,
--   the time set to zero, and os set to 255, with no extra, name, or comment
--   fields.  The gzip header is returned to the default state by deflateReset().
--
--     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent.
--*/
--
--/*
--ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
--                                     int  windowBits));
--
--     This is another version of inflateInit with an extra parameter.  The
--   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
--   before by the caller.
--
--     The windowBits parameter is the base two logarithm of the maximum window
--   size (the size of the history buffer).  It should be in the range 8..15 for
--   this version of the library.  The default value is 15 if inflateInit is used
--   instead.  windowBits must be greater than or equal to the windowBits value
--   provided to deflateInit2() while compressing, or it must be equal to 15 if
--   deflateInit2() was not used.  If a compressed stream with a larger window
--   size is given as input, inflate() will return with the error code
--   Z_DATA_ERROR instead of trying to allocate a larger window.
--
--     windowBits can also be zero to request that inflate use the window size in
--   the zlib header of the compressed stream.
--
--     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
--   determines the window size.  inflate() will then process raw deflate data,
--   not looking for a zlib or gzip header, not generating a check value, and not
--   looking for any check values for comparison at the end of the stream.  This
--   is for use with other formats that use the deflate compressed data format
--   such as zip.  Those formats provide their own check values.  If a custom
--   format is developed using the raw deflate format for compressed data, it is
--   recommended that a check value such as an Adler-32 or a CRC-32 be applied to
--   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
--   most applications, the zlib format should be used as is.  Note that comments
--   above on the use in deflateInit2() applies to the magnitude of windowBits.
--
--     windowBits can also be greater than 15 for optional gzip decoding.  Add
--   32 to windowBits to enable zlib and gzip decoding with automatic header
--   detection, or add 16 to decode only the gzip format (the zlib format will
--   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
--   CRC-32 instead of an Adler-32.  Unlike the gunzip utility and gzread() (see
--   below), inflate() will not automatically decode concatenated gzip streams.
--   inflate() will return Z_STREAM_END at the end of the gzip stream.  The state
--   would need to be reset to continue decoding a subsequent gzip stream.
--
--     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
--   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
--   invalid, such as a null pointer to the structure.  msg is set to null if
--   there is no error message.  inflateInit2 does not perform any decompression
--   apart from possibly reading the zlib header if present: actual decompression
--   will be done by inflate().  (So next_in and avail_in may be modified, but
--   next_out and avail_out are unused and unchanged.) The current implementation
--   of inflateInit2() does not process any header information -- that is
--   deferred until inflate() is called.
--*/
--
--ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
--                                             const Bytef *dictionary,
--                                             uInt  dictLength));
--/*
--     Initializes the decompression dictionary from the given uncompressed byte
--   sequence.  This function must be called immediately after a call of inflate,
--   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
--   can be determined from the Adler-32 value returned by that call of inflate.
--   The compressor and decompressor must use exactly the same dictionary (see
--   deflateSetDictionary).  For raw inflate, this function can be called at any
--   time to set the dictionary.  If the provided dictionary is smaller than the
--   window and there is already data in the window, then the provided dictionary
--   will amend what's there.  The application must insure that the dictionary
--   that was used for compression is provided.
--
--     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
--   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
--   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
--   expected one (incorrect Adler-32 value).  inflateSetDictionary does not
--   perform any decompression: this will be done by subsequent calls of
--   inflate().
--*/
--
--ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm,
--                                             Bytef *dictionary,
--                                             uInt  *dictLength));
--/*
--     Returns the sliding dictionary being maintained by inflate.  dictLength is
--   set to the number of bytes in the dictionary, and that many bytes are copied
--   to dictionary.  dictionary must have enough space, where 32768 bytes is
--   always enough.  If inflateGetDictionary() is called with dictionary equal to
--   Z_NULL, then only the dictionary length is returned, and nothing is copied.
--   Similary, if dictLength is Z_NULL, then it is not set.
--
--     inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
--   stream state is inconsistent.
--*/
--
--ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
--/*
--     Skips invalid compressed data until a possible full flush point (see above
--   for the description of deflate with Z_FULL_FLUSH) can be found, or until all
--   available input is skipped.  No output is provided.
--
--     inflateSync searches for a 00 00 FF FF pattern in the compressed data.
--   All full flush points have this pattern, but not all occurrences of this
--   pattern are full flush points.
--
--     inflateSync returns Z_OK if a possible full flush point has been found,
--   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
--   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
--   In the success case, the application may save the current current value of
--   total_in which indicates where valid compressed data was found.  In the
--   error case, the application may repeatedly call inflateSync, providing more
--   input each time, until success or end of the input data.
--*/
--
--ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
--                                    z_streamp source));
--/*
--     Sets the destination stream as a complete copy of the source stream.
--
--     This function can be useful when randomly accessing a large stream.  The
--   first pass through the stream can periodically record the inflate state,
--   allowing restarting inflate at those points when randomly accessing the
--   stream.
--
--     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
--   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
--   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
--   destination.
--*/
--
--ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
--/*
--     This function is equivalent to inflateEnd followed by inflateInit,
--   but does not free and reallocate the internal decompression state.  The
--   stream will keep attributes that may have been set by inflateInit2.
--
--     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent (such as zalloc or state being Z_NULL).
--*/
--
--ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
--                                      int windowBits));
--/*
--     This function is the same as inflateReset, but it also permits changing
--   the wrap and window size requests.  The windowBits parameter is interpreted
--   the same as it is for inflateInit2.  If the window size is changed, then the
--   memory allocated for the window is freed, and the window will be reallocated
--   by inflate() if needed.
--
--     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
--   the windowBits parameter is invalid.
--*/
--
--ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
--                                     int bits,
--                                     int value));
--/*
--     This function inserts bits in the inflate input stream.  The intent is
--   that this function is used to start inflating at a bit position in the
--   middle of a byte.  The provided bits will be used before any bytes are used
--   from next_in.  This function should only be used with raw inflate, and
--   should be used before the first inflate() call after inflateInit2() or
--   inflateReset().  bits must be less than or equal to 16, and that many of the
--   least significant bits of value will be inserted in the input.
--
--     If bits is negative, then the input stream bit buffer is emptied.  Then
--   inflatePrime() can be called again to put bits in the buffer.  This is used
--   to clear out bits leftover after feeding inflate a block description prior
--   to feeding inflate codes.
--
--     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent.
--*/
--
--ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
--/*
--     This function returns two values, one in the lower 16 bits of the return
--   value, and the other in the remaining upper bits, obtained by shifting the
--   return value down 16 bits.  If the upper value is -1 and the lower value is
--   zero, then inflate() is currently decoding information outside of a block.
--   If the upper value is -1 and the lower value is non-zero, then inflate is in
--   the middle of a stored block, with the lower value equaling the number of
--   bytes from the input remaining to copy.  If the upper value is not -1, then
--   it is the number of bits back from the current bit position in the input of
--   the code (literal or length/distance pair) currently being processed.  In
--   that case the lower value is the number of bytes already emitted for that
--   code.
--
--     A code is being processed if inflate is waiting for more input to complete
--   decoding of the code, or if it has completed decoding but is waiting for
--   more output space to write the literal or match data.
--
--     inflateMark() is used to mark locations in the input data for random
--   access, which may be at bit positions, and to note those cases where the
--   output of a code may span boundaries of random access blocks.  The current
--   location in the input stream can be determined from avail_in and data_type
--   as noted in the description for the Z_BLOCK flush parameter for inflate.
--
--     inflateMark returns the value noted above, or -65536 if the provided
--   source stream state was inconsistent.
--*/
--
--ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
--                                         gz_headerp head));
--/*
--     inflateGetHeader() requests that gzip header information be stored in the
--   provided gz_header structure.  inflateGetHeader() may be called after
--   inflateInit2() or inflateReset(), and before the first call of inflate().
--   As inflate() processes the gzip stream, head->done is zero until the header
--   is completed, at which time head->done is set to one.  If a zlib stream is
--   being decoded, then head->done is set to -1 to indicate that there will be
--   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
--   used to force inflate() to return immediately after header processing is
--   complete and before any actual data is decompressed.
--
--     The text, time, xflags, and os fields are filled in with the gzip header
--   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
--   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
--   contains the maximum number of bytes to write to extra.  Once done is true,
--   extra_len contains the actual extra field length, and extra contains the
--   extra field, or that field truncated if extra_max is less than extra_len.
--   If name is not Z_NULL, then up to name_max characters are written there,
--   terminated with a zero unless the length is greater than name_max.  If
--   comment is not Z_NULL, then up to comm_max characters are written there,
--   terminated with a zero unless the length is greater than comm_max.  When any
--   of extra, name, or comment are not Z_NULL and the respective field is not
--   present in the header, then that field is set to Z_NULL to signal its
--   absence.  This allows the use of deflateSetHeader() with the returned
--   structure to duplicate the header.  However if those fields are set to
--   allocated memory, then the application will need to save those pointers
--   elsewhere so that they can be eventually freed.
--
--     If inflateGetHeader is not used, then the header information is simply
--   discarded.  The header is always checked for validity, including the header
--   CRC if present.  inflateReset() will reset the process to discard the header
--   information.  The application would need to call inflateGetHeader() again to
--   retrieve the header from the next gzip stream.
--
--     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
--   stream state was inconsistent.
--*/
--
--/*
--ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
--                                        unsigned char FAR *window));
--
--     Initialize the internal stream state for decompression using inflateBack()
--   calls.  The fields zalloc, zfree and opaque in strm must be initialized
--   before the call.  If zalloc and zfree are Z_NULL, then the default library-
--   derived memory allocation routines are used.  windowBits is the base two
--   logarithm of the window size, in the range 8..15.  window is a caller
--   supplied buffer of that size.  Except for special applications where it is
--   assured that deflate was used with small window sizes, windowBits must be 15
--   and a 32K byte window must be supplied to be able to decompress general
--   deflate streams.
--
--     See inflateBack() for the usage of these routines.
--
--     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
--   the parameters are invalid, Z_MEM_ERROR if the internal state could not be
--   allocated, or Z_VERSION_ERROR if the version of the library does not match
--   the version of the header file.
--*/
--
--typedef unsigned (*in_func) OF((void FAR *,
--                                z_const unsigned char FAR * FAR *));
--typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
--
--ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
--                                    in_func in, void FAR *in_desc,
--                                    out_func out, void FAR *out_desc));
--/*
--     inflateBack() does a raw inflate with a single call using a call-back
--   interface for input and output.  This is potentially more efficient than
--   inflate() for file i/o applications, in that it avoids copying between the
--   output and the sliding window by simply making the window itself the output
--   buffer.  inflate() can be faster on modern CPUs when used with large
--   buffers.  inflateBack() trusts the application to not change the output
--   buffer passed by the output function, at least until inflateBack() returns.
--
--     inflateBackInit() must be called first to allocate the internal state
--   and to initialize the state with the user-provided window buffer.
--   inflateBack() may then be used multiple times to inflate a complete, raw
--   deflate stream with each call.  inflateBackEnd() is then called to free the
--   allocated state.
--
--     A raw deflate stream is one with no zlib or gzip header or trailer.
--   This routine would normally be used in a utility that reads zip or gzip
--   files and writes out uncompressed files.  The utility would decode the
--   header and process the trailer on its own, hence this routine expects only
--   the raw deflate stream to decompress.  This is different from the default
--   behavior of inflate(), which expects a zlib header and trailer around the
--   deflate stream.
--
--     inflateBack() uses two subroutines supplied by the caller that are then
--   called by inflateBack() for input and output.  inflateBack() calls those
--   routines until it reads a complete deflate stream and writes out all of the
--   uncompressed data, or until it encounters an error.  The function's
--   parameters and return types are defined above in the in_func and out_func
--   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
--   number of bytes of provided input, and a pointer to that input in buf.  If
--   there is no input available, in() must return zero -- buf is ignored in that
--   case -- and inflateBack() will return a buffer error.  inflateBack() will
--   call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].
--   out() should return zero on success, or non-zero on failure.  If out()
--   returns non-zero, inflateBack() will return with an error.  Neither in() nor
--   out() are permitted to change the contents of the window provided to
--   inflateBackInit(), which is also the buffer that out() uses to write from.
--   The length written by out() will be at most the window size.  Any non-zero
--   amount of input may be provided by in().
--
--     For convenience, inflateBack() can be provided input on the first call by
--   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
--   in() will be called.  Therefore strm->next_in must be initialized before
--   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
--   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
--   must also be initialized, and then if strm->avail_in is not zero, input will
--   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
--
--     The in_desc and out_desc parameters of inflateBack() is passed as the
--   first parameter of in() and out() respectively when they are called.  These
--   descriptors can be optionally used to pass any information that the caller-
--   supplied in() and out() functions need to do their job.
--
--     On return, inflateBack() will set strm->next_in and strm->avail_in to
--   pass back any unused input that was provided by the last in() call.  The
--   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
--   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
--   in the deflate stream (in which case strm->msg is set to indicate the nature
--   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
--   In the case of Z_BUF_ERROR, an input or output error can be distinguished
--   using strm->next_in which will be Z_NULL only if in() returned an error.  If
--   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
--   non-zero.  (in() will always be called before out(), so strm->next_in is
--   assured to be defined if out() returns non-zero.)  Note that inflateBack()
--   cannot return Z_OK.
--*/
--
--ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
--/*
--     All memory allocated by inflateBackInit() is freed.
--
--     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
--   state was inconsistent.
--*/
--
--ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
--/* Return flags indicating compile-time options.
--
--    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
--     1.0: size of uInt
--     3.2: size of uLong
--     5.4: size of voidpf (pointer)
--     7.6: size of z_off_t
--
--    Compiler, assembler, and debug options:
--     8: ZLIB_DEBUG
--     9: ASMV or ASMINF -- use ASM code
--     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
--     11: 0 (reserved)
--
--    One-time table building (smaller code, but not thread-safe if true):
--     12: BUILDFIXED -- build static block decoding tables when needed
--     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
--     14,15: 0 (reserved)
--
--    Library content (indicates missing functionality):
--     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
--                          deflate code when not needed)
--     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
--                    and decode gzip streams (to avoid linking crc code)
--     18-19: 0 (reserved)
--
--    Operation variations (changes in library functionality):
--     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
--     21: FASTEST -- deflate algorithm with only one, lowest compression level
--     22,23: 0 (reserved)
--
--    The sprintf variant used by gzprintf (zero is best):
--     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
--     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
--     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
--
--    Remainder:
--     27-31: 0 (reserved)
-- */
--
--#ifndef Z_SOLO
--
--                        /* utility functions */
--
--/*
--     The following utility functions are implemented on top of the basic
--   stream-oriented functions.  To simplify the interface, some default options
--   are assumed (compression level and memory usage, standard memory allocation
--   functions).  The source code of these utility functions can be modified if
--   you need special options.
--*/
--
--ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
--                                 const Bytef *source, uLong sourceLen));
--/*
--     Compresses the source buffer into the destination buffer.  sourceLen is
--   the byte length of the source buffer.  Upon entry, destLen is the total size
--   of the destination buffer, which must be at least the value returned by
--   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
--   compressed data.  compress() is equivalent to compress2() with a level
--   parameter of Z_DEFAULT_COMPRESSION.
--
--     compress returns Z_OK if success, Z_MEM_ERROR if there was not
--   enough memory, Z_BUF_ERROR if there was not enough room in the output
--   buffer.
--*/
--
--ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
--                                  const Bytef *source, uLong sourceLen,
--                                  int level));
--/*
--     Compresses the source buffer into the destination buffer.  The level
--   parameter has the same meaning as in deflateInit.  sourceLen is the byte
--   length of the source buffer.  Upon entry, destLen is the total size of the
--   destination buffer, which must be at least the value returned by
--   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
--   compressed data.
--
--     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
--   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
--   Z_STREAM_ERROR if the level parameter is invalid.
--*/
--
--ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
--/*
--     compressBound() returns an upper bound on the compressed size after
--   compress() or compress2() on sourceLen bytes.  It would be used before a
--   compress() or compress2() call to allocate the destination buffer.
--*/
--
--ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
--                                   const Bytef *source, uLong sourceLen));
--/*
--     Decompresses the source buffer into the destination buffer.  sourceLen is
--   the byte length of the source buffer.  Upon entry, destLen is the total size
--   of the destination buffer, which must be large enough to hold the entire
--   uncompressed data.  (The size of the uncompressed data must have been saved
--   previously by the compressor and transmitted to the decompressor by some
--   mechanism outside the scope of this compression library.) Upon exit, destLen
--   is the actual size of the uncompressed data.
--
--     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
--   enough memory, Z_BUF_ERROR if there was not enough room in the output
--   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
--   the case where there is not enough room, uncompress() will fill the output
--   buffer with the uncompressed data up to that point.
--*/
--
--ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest,   uLongf *destLen,
--                                    const Bytef *source, uLong *sourceLen));
--/*
--     Same as uncompress, except that sourceLen is a pointer, where the
--   length of the source is *sourceLen.  On return, *sourceLen is the number of
--   source bytes consumed.
--*/
--
--                        /* gzip file access functions */
--
--/*
--     This library supports reading and writing files in gzip (.gz) format with
--   an interface similar to that of stdio, using the functions that start with
--   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
--   wrapper, documented in RFC 1952, wrapped around a deflate stream.
--*/
--
--typedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */
--
--/*
--ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
--
--     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
--   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
--   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
--   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
--   for fixed code compression as in "wb9F".  (See the description of
--   deflateInit2 for more information about the strategy parameter.)  'T' will
--   request transparent writing or appending with no compression and not using
--   the gzip format.
--
--     "a" can be used instead of "w" to request that the gzip stream that will
--   be written be appended to the file.  "+" will result in an error, since
--   reading and writing to the same gzip file is not supported.  The addition of
--   "x" when writing will create the file exclusively, which fails if the file
--   already exists.  On systems that support it, the addition of "e" when
--   reading or writing will set the flag to close the file on an execve() call.
--
--     These functions, as well as gzip, will read and decode a sequence of gzip
--   streams in a file.  The append function of gzopen() can be used to create
--   such a file.  (Also see gzflush() for another way to do this.)  When
--   appending, gzopen does not test whether the file begins with a gzip stream,
--   nor does it look for the end of the gzip streams to begin appending.  gzopen
--   will simply append a gzip stream to the existing file.
--
--     gzopen can be used to read a file which is not in gzip format; in this
--   case gzread will directly read from the file without decompression.  When
--   reading, this will be detected automatically by looking for the magic two-
--   byte gzip header.
--
--     gzopen returns NULL if the file could not be opened, if there was
--   insufficient memory to allocate the gzFile state, or if an invalid mode was
--   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
--   errno can be checked to determine if the reason gzopen failed was that the
--   file could not be opened.
--*/
--
--ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
--/*
--     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
--   are obtained from calls like open, dup, creat, pipe or fileno (if the file
--   has been previously opened with fopen).  The mode parameter is as in gzopen.
--
--     The next call of gzclose on the returned gzFile will also close the file
--   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
--   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
--   mode);.  The duplicated descriptor should be saved to avoid a leak, since
--   gzdopen does not close fd if it fails.  If you are using fileno() to get the
--   file descriptor from a FILE *, then you will have to use dup() to avoid
--   double-close()ing the file descriptor.  Both gzclose() and fclose() will
--   close the associated file descriptor, so they need to have different file
--   descriptors.
--
--     gzdopen returns NULL if there was insufficient memory to allocate the
--   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
--   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
--   used until the next gz* read, write, seek, or close operation, so gzdopen
--   will not detect if fd is invalid (unless fd is -1).
--*/
--
--ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
--/*
--     Set the internal buffer size used by this library's functions.  The
--   default buffer size is 8192 bytes.  This function must be called after
--   gzopen() or gzdopen(), and before any other calls that read or write the
--   file.  The buffer memory allocation is always deferred to the first read or
--   write.  Three times that size in buffer space is allocated.  A larger buffer
--   size of, for example, 64K or 128K bytes will noticeably increase the speed
--   of decompression (reading).
--
--     The new buffer size also affects the maximum length for gzprintf().
--
--     gzbuffer() returns 0 on success, or -1 on failure, such as being called
--   too late.
--*/
--
--ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
--/*
--     Dynamically update the compression level or strategy.  See the description
--   of deflateInit2 for the meaning of these parameters.  Previously provided
--   data is flushed before the parameter change.
--
--     gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not
--   opened for writing, Z_ERRNO if there is an error writing the flushed data,
--   or Z_MEM_ERROR if there is a memory allocation error.
--*/
--
--ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
--/*
--     Reads the given number of uncompressed bytes from the compressed file.  If
--   the input file is not in gzip format, gzread copies the given number of
--   bytes into the buffer directly from the file.
--
--     After reaching the end of a gzip stream in the input, gzread will continue
--   to read, looking for another gzip stream.  Any number of gzip streams may be
--   concatenated in the input file, and will all be decompressed by gzread().
--   If something other than a gzip stream is encountered after a gzip stream,
--   that remaining trailing garbage is ignored (and no error is returned).
--
--     gzread can be used to read a gzip file that is being concurrently written.
--   Upon reaching the end of the input, gzread will return with the available
--   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
--   gzclearerr can be used to clear the end of file indicator in order to permit
--   gzread to be tried again.  Z_OK indicates that a gzip stream was completed
--   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the
--   middle of a gzip stream.  Note that gzread does not return -1 in the event
--   of an incomplete gzip stream.  This error is deferred until gzclose(), which
--   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
--   stream.  Alternatively, gzerror can be used before gzclose to detect this
--   case.
--
--     gzread returns the number of uncompressed bytes actually read, less than
--   len for end of file, or -1 for error.  If len is too large to fit in an int,
--   then nothing is read, -1 is returned, and the error state is set to
--   Z_STREAM_ERROR.
--*/
--
--ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems,
--                                     gzFile file));
--/*
--     Read up to nitems items of size size from file to buf, otherwise operating
--   as gzread() does.  This duplicates the interface of stdio's fread(), with
--   size_t request and return types.  If the library defines size_t, then
--   z_size_t is identical to size_t.  If not, then z_size_t is an unsigned
--   integer type that can contain a pointer.
--
--     gzfread() returns the number of full items read of size size, or zero if
--   the end of the file was reached and a full item could not be read, or if
--   there was an error.  gzerror() must be consulted if zero is returned in
--   order to determine if there was an error.  If the multiplication of size and
--   nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
--   is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
--
--     In the event that the end of file is reached and only a partial item is
--   available at the end, i.e. the remaining uncompressed data length is not a
--   multiple of size, then the final partial item is nevetheless read into buf
--   and the end-of-file flag is set.  The length of the partial item read is not
--   provided, but could be inferred from the result of gztell().  This behavior
--   is the same as the behavior of fread() implementations in common libraries,
--   but it prevents the direct use of gzfread() to read a concurrently written
--   file, reseting and retrying on end-of-file, when size is not 1.
--*/
--
--ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
--                                voidpc buf, unsigned len));
--/*
--     Writes the given number of uncompressed bytes into the compressed file.
--   gzwrite returns the number of uncompressed bytes written or 0 in case of
--   error.
--*/
--
--ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size,
--                                      z_size_t nitems, gzFile file));
--/*
--     gzfwrite() writes nitems items of size size from buf to file, duplicating
--   the interface of stdio's fwrite(), with size_t request and return types.  If
--   the library defines size_t, then z_size_t is identical to size_t.  If not,
--   then z_size_t is an unsigned integer type that can contain a pointer.
--
--     gzfwrite() returns the number of full items written of size size, or zero
--   if there was an error.  If the multiplication of size and nitems overflows,
--   i.e. the product does not fit in a z_size_t, then nothing is written, zero
--   is returned, and the error state is set to Z_STREAM_ERROR.
--*/
--
--ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));
--/*
--     Converts, formats, and writes the arguments to the compressed file under
--   control of the format string, as in fprintf.  gzprintf returns the number of
--   uncompressed bytes actually written, or a negative zlib error code in case
--   of error.  The number of uncompressed bytes written is limited to 8191, or
--   one less than the buffer size given to gzbuffer().  The caller should assure
--   that this limit is not exceeded.  If it is exceeded, then gzprintf() will
--   return an error (0) with nothing written.  In this case, there may also be a
--   buffer overflow with unpredictable consequences, which is possible only if
--   zlib was compiled with the insecure functions sprintf() or vsprintf()
--   because the secure snprintf() or vsnprintf() functions were not available.
--   This can be determined using zlibCompileFlags().
--*/
--
--ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
--/*
--     Writes the given null-terminated string to the compressed file, excluding
--   the terminating null character.
--
--     gzputs returns the number of characters written, or -1 in case of error.
--*/
--
--ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
--/*
--     Reads bytes from the compressed file until len-1 characters are read, or a
--   newline character is read and transferred to buf, or an end-of-file
--   condition is encountered.  If any characters are read or if len == 1, the
--   string is terminated with a null character.  If no characters are read due
--   to an end-of-file or len < 1, then the buffer is left untouched.
--
--     gzgets returns buf which is a null-terminated string, or it returns NULL
--   for end-of-file or in case of error.  If there was an error, the contents at
--   buf are indeterminate.
--*/
--
--ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
--/*
--     Writes c, converted to an unsigned char, into the compressed file.  gzputc
--   returns the value that was written, or -1 in case of error.
--*/
--
--ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
--/*
--     Reads one byte from the compressed file.  gzgetc returns this byte or -1
--   in case of end of file or error.  This is implemented as a macro for speed.
--   As such, it does not do all of the checking the other functions do.  I.e.
--   it does not check to see if file is NULL, nor whether the structure file
--   points to has been clobbered or not.
--*/
--
--ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
--/*
--     Push one character back onto the stream to be read as the first character
--   on the next read.  At least one character of push-back is allowed.
--   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
--   fail if c is -1, and may fail if a character has been pushed but not read
--   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
--   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
--   The pushed character will be discarded if the stream is repositioned with
--   gzseek() or gzrewind().
--*/
--
--ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
--/*
--     Flushes all pending output into the compressed file.  The parameter flush
--   is as in the deflate() function.  The return value is the zlib error number
--   (see function gzerror below).  gzflush is only permitted when writing.
--
--     If the flush parameter is Z_FINISH, the remaining data is written and the
--   gzip stream is completed in the output.  If gzwrite() is called again, a new
--   gzip stream will be started in the output.  gzread() is able to read such
--   concatenated gzip streams.
--
--     gzflush should be called only when strictly necessary because it will
--   degrade compression if called too often.
--*/
--
--/*
--ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
--                                   z_off_t offset, int whence));
--
--     Sets the starting position for the next gzread or gzwrite on the given
--   compressed file.  The offset represents a number of bytes in the
--   uncompressed data stream.  The whence parameter is defined as in lseek(2);
--   the value SEEK_END is not supported.
--
--     If the file is opened for reading, this function is emulated but can be
--   extremely slow.  If the file is opened for writing, only forward seeks are
--   supported; gzseek then compresses a sequence of zeroes up to the new
--   starting position.
--
--     gzseek returns the resulting offset location as measured in bytes from
--   the beginning of the uncompressed stream, or -1 in case of error, in
--   particular if the file is opened for writing and the new starting position
--   would be before the current position.
--*/
--
--ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
--/*
--     Rewinds the given file. This function is supported only for reading.
--
--     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
--*/
--
--/*
--ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
--
--     Returns the starting position for the next gzread or gzwrite on the given
--   compressed file.  This position represents a number of bytes in the
--   uncompressed data stream, and is zero when starting, even if appending or
--   reading a gzip stream from the middle of a file using gzdopen().
--
--     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
--*/
--
--/*
--ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
--
--     Returns the current offset in the file being read or written.  This offset
--   includes the count of bytes that precede the gzip stream, for example when
--   appending or when using gzdopen() for reading.  When reading, the offset
--   does not include as yet unused buffered input.  This information can be used
--   for a progress indicator.  On error, gzoffset() returns -1.
--*/
--
--ZEXTERN int ZEXPORT gzeof OF((gzFile file));
--/*
--     Returns true (1) if the end-of-file indicator has been set while reading,
--   false (0) otherwise.  Note that the end-of-file indicator is set only if the
--   read tried to go past the end of the input, but came up short.  Therefore,
--   just like feof(), gzeof() may return false even if there is no more data to
--   read, in the event that the last read request was for the exact number of
--   bytes remaining in the input file.  This will happen if the input file size
--   is an exact multiple of the buffer size.
--
--     If gzeof() returns true, then the read functions will return no more data,
--   unless the end-of-file indicator is reset by gzclearerr() and the input file
--   has grown since the previous end of file was detected.
--*/
--
--ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
--/*
--     Returns true (1) if file is being copied directly while reading, or false
--   (0) if file is a gzip stream being decompressed.
--
--     If the input file is empty, gzdirect() will return true, since the input
--   does not contain a gzip stream.
--
--     If gzdirect() is used immediately after gzopen() or gzdopen() it will
--   cause buffers to be allocated to allow reading the file to determine if it
--   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
--   gzdirect().
--
--     When writing, gzdirect() returns true (1) if transparent writing was
--   requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
--   gzdirect() is not needed when writing.  Transparent writing must be
--   explicitly requested, so the application already knows the answer.  When
--   linking statically, using gzdirect() will include all of the zlib code for
--   gzip file reading and decompression, which may not be desired.)
--*/
--
--ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
--/*
--     Flushes all pending output if necessary, closes the compressed file and
--   deallocates the (de)compression state.  Note that once file is closed, you
--   cannot call gzerror with file, since its structures have been deallocated.
--   gzclose must not be called more than once on the same file, just as free
--   must not be called more than once on the same allocation.
--
--     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
--   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
--   last read ended in the middle of a gzip stream, or Z_OK on success.
--*/
--
--ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
--ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
--/*
--     Same as gzclose(), but gzclose_r() is only for use when reading, and
--   gzclose_w() is only for use when writing or appending.  The advantage to
--   using these instead of gzclose() is that they avoid linking in zlib
--   compression or decompression code that is not used when only reading or only
--   writing respectively.  If gzclose() is used, then both compression and
--   decompression code will be included the application when linking to a static
--   zlib library.
--*/
--
--ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
--/*
--     Returns the error message for the last error which occurred on the given
--   compressed file.  errnum is set to zlib error number.  If an error occurred
--   in the file system and not in the compression library, errnum is set to
--   Z_ERRNO and the application may consult errno to get the exact error code.
--
--     The application must not modify the returned string.  Future calls to
--   this function may invalidate the previously returned string.  If file is
--   closed, then the string previously returned by gzerror will no longer be
--   available.
--
--     gzerror() should be used to distinguish errors from end-of-file for those
--   functions above that do not distinguish those cases in their return values.
--*/
--
--ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
--/*
--     Clears the error and end-of-file flags for file.  This is analogous to the
--   clearerr() function in stdio.  This is useful for continuing to read a gzip
--   file that is being written concurrently.
--*/
--
--#endif /* !Z_SOLO */
--
--                        /* checksum functions */
--
--/*
--     These functions are not related to compression but are exported
--   anyway because they might be useful in applications using the compression
--   library.
--*/
--
--ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
--/*
--     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
--   return the updated checksum.  If buf is Z_NULL, this function returns the
--   required initial value for the checksum.
--
--     An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed
--   much faster.
--
--   Usage example:
--
--     uLong adler = adler32(0L, Z_NULL, 0);
--
--     while (read_buffer(buffer, length) != EOF) {
--       adler = adler32(adler, buffer, length);
--     }
--     if (adler != original_adler) error();
--*/
--
--ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf,
--                                    z_size_t len));
--/*
--     Same as adler32(), but with a size_t length.
--*/
--
--/*
--ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
--                                          z_off_t len2));
--
--     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
--   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
--   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
--   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note
--   that the z_off_t type (like off_t) is a signed integer.  If len2 is
--   negative, the result has no meaning or utility.
--*/
--
--ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
--/*
--     Update a running CRC-32 with the bytes buf[0..len-1] and return the
--   updated CRC-32.  If buf is Z_NULL, this function returns the required
--   initial value for the crc.  Pre- and post-conditioning (one's complement) is
--   performed within this function so it shouldn't be done by the application.
--
--   Usage example:
--
--     uLong crc = crc32(0L, Z_NULL, 0);
--
--     while (read_buffer(buffer, length) != EOF) {
--       crc = crc32(crc, buffer, length);
--     }
--     if (crc != original_crc) error();
--*/
--
--ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf,
--                                  z_size_t len));
--/*
--     Same as crc32(), but with a size_t length.
--*/
--
--/*
--ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
--
--     Combine two CRC-32 check values into one.  For two sequences of bytes,
--   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
--   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
--   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
--   len2.
--*/
--
--
--                        /* various hacks, don't look :) */
--
--/* deflateInit and inflateInit are macros to allow checking the zlib version
-- * and the compiler's view of z_stream:
-- */
--ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
--                                     const char *version, int stream_size));
--ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
--                                     const char *version, int stream_size));
--ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
--                                      int windowBits, int memLevel,
--                                      int strategy, const char *version,
--                                      int stream_size));
--ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
--                                      const char *version, int stream_size));
--ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
--                                         unsigned char FAR *window,
--                                         const char *version,
--                                         int stream_size));
--#ifdef Z_PREFIX_SET
--#  define z_deflateInit(strm, level) \
--          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
--#  define z_inflateInit(strm) \
--          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
--#  define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
--          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
--                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
--#  define z_inflateInit2(strm, windowBits) \
--          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
--                        (int)sizeof(z_stream))
--#  define z_inflateBackInit(strm, windowBits, window) \
--          inflateBackInit_((strm), (windowBits), (window), \
--                           ZLIB_VERSION, (int)sizeof(z_stream))
--#else
--#  define deflateInit(strm, level) \
--          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
--#  define inflateInit(strm) \
--          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
--#  define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
--          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
--                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
--#  define inflateInit2(strm, windowBits) \
--          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
--                        (int)sizeof(z_stream))
--#  define inflateBackInit(strm, windowBits, window) \
--          inflateBackInit_((strm), (windowBits), (window), \
--                           ZLIB_VERSION, (int)sizeof(z_stream))
--#endif
--
--#ifndef Z_SOLO
--
--/* gzgetc() macro and its supporting function and exposed data structure.  Note
-- * that the real internal state is much larger than the exposed structure.
-- * This abbreviated structure exposes just enough for the gzgetc() macro.  The
-- * user should not mess with these exposed elements, since their names or
-- * behavior could change in the future, perhaps even capriciously.  They can
-- * only be used by the gzgetc() macro.  You have been warned.
-- */
--struct gzFile_s {
--    unsigned have;
--    unsigned char *next;
--    z_off64_t pos;
--};
--ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */
--#ifdef Z_PREFIX_SET
--#  undef z_gzgetc
--#  define z_gzgetc(g) \
--          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
--#else
--#  define gzgetc(g) \
--          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
--#endif
--
--/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
-- * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
-- * both are true, the application gets the *64 functions, and the regular
-- * functions are changed to 64 bits) -- in case these are set on systems
-- * without large file support, _LFS64_LARGEFILE must also be true
-- */
--#ifdef Z_LARGE64
--   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
--   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
--   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
--   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
--   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
--   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
--#endif
--
--#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
--#  ifdef Z_PREFIX_SET
--#    define z_gzopen z_gzopen64
--#    define z_gzseek z_gzseek64
--#    define z_gztell z_gztell64
--#    define z_gzoffset z_gzoffset64
--#    define z_adler32_combine z_adler32_combine64
--#    define z_crc32_combine z_crc32_combine64
--#  else
--#    define gzopen gzopen64
--#    define gzseek gzseek64
--#    define gztell gztell64
--#    define gzoffset gzoffset64
--#    define adler32_combine adler32_combine64
--#    define crc32_combine crc32_combine64
--#  endif
--#  ifndef Z_LARGE64
--     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
--     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
--     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
--     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
--     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
--     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
--#  endif
--#else
--   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
--   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
--   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
--   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
--   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
--   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
--#endif
--
--#else /* Z_SOLO */
--
--   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
--   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
--
--#endif /* !Z_SOLO */
--
--/* undocumented functions */
--ZEXTERN const char   * ZEXPORT zError           OF((int));
--ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
--ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));
--ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
--ZEXTERN int            ZEXPORT inflateValidate OF((z_streamp, int));
--ZEXTERN unsigned long  ZEXPORT inflateCodesUsed OF ((z_streamp));
--ZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));
--ZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));
--#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO)
--ZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,
--                                            const char *mode));
--#endif
--#if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#  ifndef Z_SOLO
--ZEXTERN int            ZEXPORTVA gzvprintf Z_ARG((gzFile file,
--                                                  const char *format,
--                                                  va_list va));
--#  endif
--#endif
--
--#ifdef __cplusplus
--}
--#endif
--
--#endif /* ZLIB_H */
diff --cc zlib/zutil.c
index a76c6b0c7e557f8c29cfcf58a5ef9ef79c5e4e8a,a76c6b0c7e557f8c29cfcf58a5ef9ef79c5e4e8a..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,325 -1,325 +1,0 @@@
--/* zutil.c -- target dependent utility functions for the compression library
-- * Copyright (C) 1995-2017 Jean-loup Gailly
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* @(#) $Id$ */
--
--#include "zutil.h"
--#ifndef Z_SOLO
--#  include "gzguts.h"
--#endif
--
--z_const char * const z_errmsg[10] = {
--    (z_const char *)"need dictionary",     /* Z_NEED_DICT       2  */
--    (z_const char *)"stream end",          /* Z_STREAM_END      1  */
--    (z_const char *)"",                    /* Z_OK              0  */
--    (z_const char *)"file error",          /* Z_ERRNO         (-1) */
--    (z_const char *)"stream error",        /* Z_STREAM_ERROR  (-2) */
--    (z_const char *)"data error",          /* Z_DATA_ERROR    (-3) */
--    (z_const char *)"insufficient memory", /* Z_MEM_ERROR     (-4) */
--    (z_const char *)"buffer error",        /* Z_BUF_ERROR     (-5) */
--    (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */
--    (z_const char *)""
--};
--
--
--const char * ZEXPORT zlibVersion()
--{
--    return ZLIB_VERSION;
--}
--
--uLong ZEXPORT zlibCompileFlags()
--{
--    uLong flags;
--
--    flags = 0;
--    switch ((int)(sizeof(uInt))) {
--    case 2:     break;
--    case 4:     flags += 1;     break;
--    case 8:     flags += 2;     break;
--    default:    flags += 3;
--    }
--    switch ((int)(sizeof(uLong))) {
--    case 2:     break;
--    case 4:     flags += 1 << 2;        break;
--    case 8:     flags += 2 << 2;        break;
--    default:    flags += 3 << 2;
--    }
--    switch ((int)(sizeof(voidpf))) {
--    case 2:     break;
--    case 4:     flags += 1 << 4;        break;
--    case 8:     flags += 2 << 4;        break;
--    default:    flags += 3 << 4;
--    }
--    switch ((int)(sizeof(z_off_t))) {
--    case 2:     break;
--    case 4:     flags += 1 << 6;        break;
--    case 8:     flags += 2 << 6;        break;
--    default:    flags += 3 << 6;
--    }
--#ifdef ZLIB_DEBUG
--    flags += 1 << 8;
--#endif
--#if defined(ASMV) || defined(ASMINF)
--    flags += 1 << 9;
--#endif
--#ifdef ZLIB_WINAPI
--    flags += 1 << 10;
--#endif
--#ifdef BUILDFIXED
--    flags += 1 << 12;
--#endif
--#ifdef DYNAMIC_CRC_TABLE
--    flags += 1 << 13;
--#endif
--#ifdef NO_GZCOMPRESS
--    flags += 1L << 16;
--#endif
--#ifdef NO_GZIP
--    flags += 1L << 17;
--#endif
--#ifdef PKZIP_BUG_WORKAROUND
--    flags += 1L << 20;
--#endif
--#ifdef FASTEST
--    flags += 1L << 21;
--#endif
--#if defined(STDC) || defined(Z_HAVE_STDARG_H)
--#  ifdef NO_vsnprintf
--    flags += 1L << 25;
--#    ifdef HAS_vsprintf_void
--    flags += 1L << 26;
--#    endif
--#  else
--#    ifdef HAS_vsnprintf_void
--    flags += 1L << 26;
--#    endif
--#  endif
--#else
--    flags += 1L << 24;
--#  ifdef NO_snprintf
--    flags += 1L << 25;
--#    ifdef HAS_sprintf_void
--    flags += 1L << 26;
--#    endif
--#  else
--#    ifdef HAS_snprintf_void
--    flags += 1L << 26;
--#    endif
--#  endif
--#endif
--    return flags;
--}
--
--#ifdef ZLIB_DEBUG
--#include <stdlib.h>
--#  ifndef verbose
--#    define verbose 0
--#  endif
--int ZLIB_INTERNAL z_verbose = verbose;
--
--void ZLIB_INTERNAL z_error (m)
--    char *m;
--{
--    fprintf(stderr, "%s\n", m);
--    exit(1);
--}
--#endif
--
--/* exported to allow conversion of error code to string for compress() and
-- * uncompress()
-- */
--const char * ZEXPORT zError(err)
--    int err;
--{
--    return ERR_MSG(err);
--}
--
--#if defined(_WIN32_WCE)
--    /* The Microsoft C Run-Time Library for Windows CE doesn't have
--     * errno.  We define it as a global variable to simplify porting.
--     * Its value is always 0 and should not be used.
--     */
--    int errno = 0;
--#endif
--
--#ifndef HAVE_MEMCPY
--
--void ZLIB_INTERNAL zmemcpy(dest, source, len)
--    Bytef* dest;
--    const Bytef* source;
--    uInt  len;
--{
--    if (len == 0) return;
--    do {
--        *dest++ = *source++; /* ??? to be unrolled */
--    } while (--len != 0);
--}
--
--int ZLIB_INTERNAL zmemcmp(s1, s2, len)
--    const Bytef* s1;
--    const Bytef* s2;
--    uInt  len;
--{
--    uInt j;
--
--    for (j = 0; j < len; j++) {
--        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
--    }
--    return 0;
--}
--
--void ZLIB_INTERNAL zmemzero(dest, len)
--    Bytef* dest;
--    uInt  len;
--{
--    if (len == 0) return;
--    do {
--        *dest++ = 0;  /* ??? to be unrolled */
--    } while (--len != 0);
--}
--#endif
--
--#ifndef Z_SOLO
--
--#ifdef SYS16BIT
--
--#ifdef __TURBOC__
--/* Turbo C in 16-bit mode */
--
--#  define MY_ZCALLOC
--
--/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
-- * and farmalloc(64K) returns a pointer with an offset of 8, so we
-- * must fix the pointer. Warning: the pointer must be put back to its
-- * original form in order to free it, use zcfree().
-- */
--
--#define MAX_PTR 10
--/* 10*64K = 640K */
--
--local int next_ptr = 0;
--
--typedef struct ptr_table_s {
--    voidpf org_ptr;
--    voidpf new_ptr;
--} ptr_table;
--
--local ptr_table table[MAX_PTR];
--/* This table is used to remember the original form of pointers
-- * to large buffers (64K). Such pointers are normalized with a zero offset.
-- * Since MSDOS is not a preemptive multitasking OS, this table is not
-- * protected from concurrent access. This hack doesn't work anyway on
-- * a protected system like OS/2. Use Microsoft C instead.
-- */
--
--voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
--{
--    voidpf buf;
--    ulg bsize = (ulg)items*size;
--
--    (void)opaque;
--
--    /* If we allocate less than 65520 bytes, we assume that farmalloc
--     * will return a usable pointer which doesn't have to be normalized.
--     */
--    if (bsize < 65520L) {
--        buf = farmalloc(bsize);
--        if (*(ush*)&buf != 0) return buf;
--    } else {
--        buf = farmalloc(bsize + 16L);
--    }
--    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
--    table[next_ptr].org_ptr = buf;
--
--    /* Normalize the pointer to seg:0 */
--    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
--    *(ush*)&buf = 0;
--    table[next_ptr++].new_ptr = buf;
--    return buf;
--}
--
--void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
--{
--    int n;
--
--    (void)opaque;
--
--    if (*(ush*)&ptr != 0) { /* object < 64K */
--        farfree(ptr);
--        return;
--    }
--    /* Find the original pointer */
--    for (n = 0; n < next_ptr; n++) {
--        if (ptr != table[n].new_ptr) continue;
--
--        farfree(table[n].org_ptr);
--        while (++n < next_ptr) {
--            table[n-1] = table[n];
--        }
--        next_ptr--;
--        return;
--    }
--    Assert(0, "zcfree: ptr not found");
--}
--
--#endif /* __TURBOC__ */
--
--
--#ifdef M_I86
--/* Microsoft C in 16-bit mode */
--
--#  define MY_ZCALLOC
--
--#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
--#  define _halloc  halloc
--#  define _hfree   hfree
--#endif
--
--voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
--{
--    (void)opaque;
--    return _halloc((long)items, size);
--}
--
--void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
--{
--    (void)opaque;
--    _hfree(ptr);
--}
--
--#endif /* M_I86 */
--
--#endif /* SYS16BIT */
--
--
--#ifndef MY_ZCALLOC /* Any system without a special alloc function */
--
--#ifndef STDC
--extern voidp  malloc OF((uInt size));
--extern voidp  calloc OF((uInt items, uInt size));
--extern void   free   OF((voidpf ptr));
--#endif
--
--voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
--    voidpf opaque;
--    unsigned items;
--    unsigned size;
--{
--    (void)opaque;
--    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
--                              (voidpf)calloc(items, size);
--}
--
--void ZLIB_INTERNAL zcfree (opaque, ptr)
--    voidpf opaque;
--    voidpf ptr;
--{
--    (void)opaque;
--    free(ptr);
--}
--
--#endif /* MY_ZCALLOC */
--
--#endif /* !Z_SOLO */
diff --cc zlib/zutil.h
index b079ea6a80f5abd23a6b2451d6eaee50ceda969b,b079ea6a80f5abd23a6b2451d6eaee50ceda969b..0000000000000000000000000000000000000000
deleted file mode 100644,100644
+++ /dev/null
@@@ -1,271 -1,271 +1,0 @@@
--/* zutil.h -- internal interface and configuration of the compression library
-- * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
-- * For conditions of distribution and use, see copyright notice in zlib.h
-- */
--
--/* WARNING: this file should *not* be used by applications. It is
--   part of the implementation of the compression library and is
--   subject to change. Applications should only use zlib.h.
-- */
--
--/* @(#) $Id$ */
--
--#ifndef ZUTIL_H
--#define ZUTIL_H
--
--#ifdef HAVE_HIDDEN
--#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
--#else
--#  define ZLIB_INTERNAL
--#endif
--
--#include "zlib.h"
--
--#if defined(STDC) && !defined(Z_SOLO)
--#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
--#    include <stddef.h>
--#  endif
--#  include <string.h>
--#  include <stdlib.h>
--#endif
--
--#ifdef Z_SOLO
--   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
--#endif
--
--#ifndef local
--#  define local static
--#endif
--/* since "static" is used to mean two completely different things in C, we
--   define "local" for the non-static meaning of "static", for readability
--   (compile with -Dlocal if your debugger can't find static symbols) */
--
--typedef unsigned char  uch;
--typedef uch FAR uchf;
--typedef unsigned short ush;
--typedef ush FAR ushf;
--typedef unsigned long  ulg;
--
--extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
--/* (size given to avoid silly warnings with Visual C++) */
--
--#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
--
--#define ERR_RETURN(strm,err) \
--  return (strm->msg = ERR_MSG(err), (err))
--/* To be used only when the state is known to be valid */
--
--        /* common constants */
--
--#ifndef DEF_WBITS
--#  define DEF_WBITS MAX_WBITS
--#endif
--/* default windowBits for decompression. MAX_WBITS is for compression only */
--
--#if MAX_MEM_LEVEL >= 8
--#  define DEF_MEM_LEVEL 8
--#else
--#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
--#endif
--/* default memLevel */
--
--#define STORED_BLOCK 0
--#define STATIC_TREES 1
--#define DYN_TREES    2
--/* The three kinds of block type */
--
--#define MIN_MATCH  3
--#define MAX_MATCH  258
--/* The minimum and maximum match lengths */
--
--#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
--
--        /* target dependencies */
--
--#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
--#  define OS_CODE  0x00
--#  ifndef Z_SOLO
--#    if defined(__TURBOC__) || defined(__BORLANDC__)
--#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
--         /* Allow compilation with ANSI keywords only enabled */
--         void _Cdecl farfree( void *block );
--         void *_Cdecl farmalloc( unsigned long nbytes );
--#      else
--#        include <alloc.h>
--#      endif
--#    else /* MSC or DJGPP */
--#      include <malloc.h>
--#    endif
--#  endif
--#endif
--
--#ifdef AMIGA
--#  define OS_CODE  1
--#endif
--
--#if defined(VAXC) || defined(VMS)
--#  define OS_CODE  2
--#  define F_OPEN(name, mode) \
--     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
--#endif
--
--#ifdef __370__
--#  if __TARGET_LIB__ < 0x20000000
--#    define OS_CODE 4
--#  elif __TARGET_LIB__ < 0x40000000
--#    define OS_CODE 11
--#  else
--#    define OS_CODE 8
--#  endif
--#endif
--
--#if defined(ATARI) || defined(atarist)
--#  define OS_CODE  5
--#endif
--
--#ifdef OS2
--#  define OS_CODE  6
--#  if defined(M_I86) && !defined(Z_SOLO)
--#    include <malloc.h>
--#  endif
--#endif
--
--#if defined(MACOS) || defined(TARGET_OS_MAC)
--#  define OS_CODE  7
--#  ifndef Z_SOLO
--#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
--#      include <unix.h> /* for fdopen */
--#    else
--#      ifndef fdopen
--#        define fdopen(fd,mode) NULL /* No fdopen() */
--#      endif
--#    endif
--#  endif
--#endif
--
--#ifdef __acorn
--#  define OS_CODE 13
--#endif
--
--#if defined(WIN32) && !defined(__CYGWIN__)
--#  define OS_CODE  10
--#endif
--
--#ifdef _BEOS_
--#  define OS_CODE  16
--#endif
--
--#ifdef __TOS_OS400__
--#  define OS_CODE 18
--#endif
--
--#ifdef __APPLE__
--#  define OS_CODE 19
--#endif
--
--#if defined(_BEOS_) || defined(RISCOS)
--#  define fdopen(fd,mode) NULL /* No fdopen() */
--#endif
--
--#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
--#  if defined(_WIN32_WCE)
--#    define fdopen(fd,mode) NULL /* No fdopen() */
--#    ifndef _PTRDIFF_T_DEFINED
--       typedef int ptrdiff_t;
--#      define _PTRDIFF_T_DEFINED
--#    endif
--#  else
--#    define fdopen(fd,type)  _fdopen(fd,type)
--#  endif
--#endif
--
--#if defined(__BORLANDC__) && !defined(MSDOS)
--  #pragma warn -8004
--  #pragma warn -8008
--  #pragma warn -8066
--#endif
--
--/* provide prototypes for these when building zlib without LFS */
--#if !defined(_WIN32) && \
--    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
--    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
--    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
--#endif
--
--        /* common defaults */
--
--#ifndef OS_CODE
--#  define OS_CODE  3     /* assume Unix */
--#endif
--
--#ifndef F_OPEN
--#  define F_OPEN(name, mode) fopen((name), (mode))
--#endif
--
--         /* functions */
--
--#if defined(pyr) || defined(Z_SOLO)
--#  define NO_MEMCPY
--#endif
--#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
-- /* Use our own functions for small and medium model with MSC <= 5.0.
--  * You may have to use the same strategy for Borland C (untested).
--  * The __SC__ check is for Symantec.
--  */
--#  define NO_MEMCPY
--#endif
--#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
--#  define HAVE_MEMCPY
--#endif
--#ifdef HAVE_MEMCPY
--#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
--#    define zmemcpy _fmemcpy
--#    define zmemcmp _fmemcmp
--#    define zmemzero(dest, len) _fmemset(dest, 0, len)
--#  else
--#    define zmemcpy memcpy
--#    define zmemcmp memcmp
--#    define zmemzero(dest, len) memset(dest, 0, len)
--#  endif
--#else
--   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
--   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
--   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
--#endif
--
--/* Diagnostic functions */
--#ifdef ZLIB_DEBUG
--#  include <stdio.h>
--   extern int ZLIB_INTERNAL z_verbose;
--   extern void ZLIB_INTERNAL z_error OF((char *m));
--#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
--#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
--#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
--#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
--#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
--#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
--#else
--#  define Assert(cond,msg)
--#  define Trace(x)
--#  define Tracev(x)
--#  define Tracevv(x)
--#  define Tracec(c,x)
--#  define Tracecv(c,x)
--#endif
--
--#ifndef Z_SOLO
--   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
--                                    unsigned size));
--   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
--#endif
--
--#define ZALLOC(strm, items, size) \
--           (*((strm)->zalloc))((strm)->opaque, (items), (size))
--#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
--#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
--
--/* Reverse the bytes in a 32-bit value */
--#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
--                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
--
--#endif /* ZUTIL_H */